我有一个编辑文本输入的活动。当activity初始化时,显示Android键盘。在用户聚焦输入之前,键盘如何保持隐藏?


当前回答

函数隐藏键盘。

public static void hideKeyboard(Activity activity) {
    View view = activity.getCurrentFocus();

    if (view != null) {
        InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);

        inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }
}

隐藏键盘在androidmanifest .xml文件。

<activity
    android:name=".MainActivity"
    android:label="@string/app_name"
    android:theme="@style/AppTheme"
    android:windowSoftInputMode="stateHidden">

其他回答

你也可以在你有“问题”的.xml布局文件的直接父布局中编写这些代码行:

android:focusable="true"
android:focusableInTouchMode="true"

例如:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    ...
    android:focusable="true"
    android:focusableInTouchMode="true" >

    <EditText
        android:id="@+id/myEditText"
        ...
        android:hint="@string/write_here" />

    <Button
        android:id="@+id/button_ok"
        ...
        android:text="@string/ok" />
</LinearLayout>

编辑:

例如,EditText包含在另一个布局中:

<?xml version="1.0" encoding="utf-8"?>
<ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    ... >                                            <!--not here-->

    ...    <!--other elements-->

    <LinearLayout
        android:id="@+id/theDirectParent"
        ...
        android:focusable="true"
        android:focusableInTouchMode="true" >        <!--here-->

        <EditText
            android:id="@+id/myEditText"
            ...
            android:hint="@string/write_here" />

        <Button
            android:id="@+id/button_ok"
            ...
            android:text="@string/ok" />
    </LinearLayout>

</ConstraintLayout>

关键是要确保EditText不能直接对焦。 再见!: -)

只需添加AndroidManifest.xml即可

<activity android:name=".HomeActivity"  android:windowSoftInputMode="stateHidden">
</activity>

只要在你的活动中添加这个:

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
      if (getCurrentFocus() != null) {
           InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
           imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
      }
      return super.dispatchTouchEvent(ev);
}

尝试在manifest文件中声明它

<activity
    android:name=".HomeActivity"
    android:label="@string/app_name"
    android:windowSoftInputMode="stateAlwaysHidden" >

只需将其添加到manifest.xml文件中

<activity android:name=".MainActivity"
            android:windowSoftInputMode="stateHidden">

你都完成了。