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

I save the incoming ViewGroup container parameter from onCreateView as a way to access the window token for the main activity. This runs without error, but the keyboard doesn't get hidden from the call to hideSoftInputFromWindow in onStart.

最初,我try 使用充气布局而不是container,即:

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

but this threw a NullPointerException, presumably because the fragment itself isn't an activity and doesn't have a unique window token?

有没有办法从片段中隐藏软键盘,或者我应该在FragmentActivity中创建一个方法,然后从片段中调用它?

推荐答案

As long as your Fragment creates a View, you can use the IBinder (window token) from that view after it has been attached. For example, you can override onActivityCreated in your Fragment:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    final InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
}

Kotlin相关问答推荐

Kotlin-删除按钮周围的空格

导入org.gradle.jvm.toolchain.internal.JavaToolchainFactory未解析引用:Java工具链工厂

Kotlin 海峡没有结束

Java/Kotlin中类似Rust般的注释编译?

为什么我的通用Kotlin函数中的这个转换未经判断?

垂直滚动条下拉菜单的桌面组合

如何在 Jetpack Compose 中启动和停止动画

使用 Compose for Desktop Bundle 文件

Kotlin 中列表或数组的乘积

Dagger 2 ContributesAndroidInjector 为模块提供活动

如何为你的 Flutter 元素添加 Kotlin 支持?

有没有办法重用 Job 实例?

Anko 中的水平线性布局

如何在 Kotlin 文件中的 Android Studio 中控制何时将 Imports 替换为通配符

如何在 Kotlin 中创建一个打开新活动(Android Studio)的按钮?

使用 clear() 删除 EncryptedSharedPreferences 不起作用

有没有办法在数据类构建时转换属性的值?

如何为kotlin异常生成SerialVersionId?

Jetpack Compose 折叠工具栏

如何将 Kotlin 的 `with` 表达式用于可空类型