我有一个 FragmentActivity
使用 ViewPager
来提供几个片段。每个都是一个 ListFragment
具有以下布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp">
<ListView android:id="@id/android:list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<EditText android:id="@+id/entertext"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
启动活动时,会显示软键盘。为了解决这个问题,我在片段中做了以下操作:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Save the container view so we can access the window token
viewContainer = container;
//get the input method manager service
imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
. . .
}
@Override
public void onStart() {
super.onStart();
//Hide the soft keyboard
imm.hideSoftInputFromWindow(viewContainer.getWindowToken(), 0);
}
我将来自 onCreateView
的传入 ViewGroup container
参数保存为访问主要活动的窗口令牌的一种方式。这运行没有错误,但键盘不会从 hideSoftInputFromWindow
在 onStart
的调用中隐藏。
最初,我尝试使用膨胀布局而不是 container
,即:
imm.hideSoftInputFromWindow(myInflatedLayout.getWindowToken(), 0);
但这引发了 NullPointerException
,大概是因为片段本身不是活动并且没有唯一的窗口令牌?
有没有办法从片段中隐藏软键盘,或者我应该在 FragmentActivity
中创建一个方法并从片段中调用它?
原文由 WilHall 发布,翻译遵循 CC BY-SA 4.0 许可协议
只要您的 Fragment 创建了一个视图,您就可以在附加视图 后 使用该视图中的 IBinder(窗口令牌)。例如,您可以在片段中覆盖 onActivityCreated: