我有一个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容器参数作为一种访问主活动窗口令牌的方式。虽然没有错误,但是在onStart中调用hideSoftInputFromWindow时,键盘并没有隐藏。
最初,我尝试使用充气布局而不是container,即:
imm.hideSoftInputFromWindow(myInflatedLayout.getWindowToken(), 0);
可是这样做会抛出NullPointerException
,可能是因为片段本身不是一个活动并且没有唯一的窗口标记吗?
是否有一种方法可以在片段内隐藏软键盘,或者我应该在FragmentActivity
中创建一个方法并从片段内调用它?