如何将软键盘隐藏在片段内?

2024-03-04

我有一个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);
}

我保存传入的ViewGroup container参数来自onCreateView作为访问主要活动的窗口令牌的一种方式。运行时没有错误,但键盘不会从调用中隐藏hideSoftInputFromWindow in onStart.

最初,我尝试使用充气布局而不是container, i.e:

imm.hideSoftInputFromWindow(myInflatedLayout.getWindowToken(), 0);

但这引发了NullPointerException,大概是因为片段本身不是活动并且没有唯一的窗口令牌?

有没有办法从片段中隐藏软键盘,或者我应该在FragmentActivity并从片段中调用它?


只要您的 Fragment 创建了一个 View,您就可以使用该视图中的 IBinder(窗口令牌)after它已被附加。例如,您可以在 Fragment 中重写 onActivityCreated:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    final InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将软键盘隐藏在片段内? 的相关文章

随机推荐