">方法三:移除 EditText
中的 <requestFocus />
确保在 EditText
的 XML 标签声明末尾移除 <requestFocus />
这一行,示例代码如下:
1 2 3 4 5 6 7 <EditText android:id ="@+id/emailField" android:layout_width ="fill_parent" android:layout_height ="wrap_content" android:inputType ="textEmailAddress" > </EditText >
方法四:使用代码控制焦点 在 onResume()
方法中使用 clearFocus()
和 requestFocus()
方法控制焦点,示例代码如下:
1 2 3 4 5 6 7 @Override protected void onResume () { super .onResume(); mAutoCompleteTextView.clearFocus(); mLinearLayout.requestFocus(); }
方法五:设置 EditText
的 focusable
属性 在 XML 中设置 EditText
的 focusable
属性为 false
,并在 Java 代码中添加触摸监听器,示例代码如下:
1 2 3 <EditText android:id ="@+id/et_bonus_custom" android:focusable ="false" />
1 2 3 4 5 6 7 8 etBonus.setOnTouchListener(new View .OnTouchListener() { @Override public boolean onTouch (View v, MotionEvent event) { v.setFocusable(true ); v.setFocusableInTouchMode(true ); return false ; } });
核心代码 父布局属性设置 1 2 3 4 <RelativeLayout xmlns:android ="http://schemas.android.com/apk/res/android" android:id ="@+id/mainLayout" android:descendantFocusability ="beforeDescendants" android:focusableInTouchMode ="true" >
窗口软输入模式设置 1 2 3 <activity android:name =".MyActivity" android:windowSoftInputMode ="stateAlwaysHidden" />
代码控制焦点 1 2 3 4 5 6 @Override protected void onResume () { super .onResume(); mAutoCompleteTextView.clearFocus(); mLinearLayout.requestFocus(); }
最佳实践 结合多种方法使用,如同时在父布局添加属性和设置窗口软输入模式。 根据具体需求选择合适的方法,例如如果只需要隐藏软键盘,可以使用 android:windowSoftInputMode
属性。 常见问题 方法无效 如果某些方法无效,可以尝试结合多种方法一起使用,或者检查代码是否存在其他影响焦点的因素。
软键盘仍然弹出 确保在 AndroidManifest.xml
中正确设置了 android:windowSoftInputMode
属性,并且移除了 EditText
中的 <requestFocus />
标签。
如何阻止 Android 活动启动时 EditText 获得焦点
https://119291.xyz/posts/2025-05-12.how-to-stop-edittext-from-gaining-focus-when-activity-starts-in-android/
博客在允许 JavaScript 运行的环境下浏览效果更佳