Android如何自动弹出软键盘?
Android如何自动弹出软键盘?
- 方法1
- 方法2
- 步骤1 添加windowSoftInputMode属性
- 步骤2 请求textinput焦点
方法1
直接在resume中控制弹出。不过需要一定的延时提交,因为需要保证当前的窗口是正在被服务的窗口。
@Override
protected void onResume() {super.onResume();// 显示软键盘textInputEditText.postDelayed(() -> {textInputEditText.requestFocus();InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);if (imm != null) {imm.showSoftInput(textInputEditText, InputMethodManager.SHOW_IMPLICIT);}}, 500);
}
显示不成功的log:
Ignoring showSoftInput() as view=com.google.android.material.textfield.TextInputEditText{5ecc3f4 VFED..CL. .F...... 0,0-1074,146 #7f0801c0 app:id/textview aid=1073741824} is not served.
方法2
系统自动管理输入法显示
步骤1 添加windowSoftInputMode属性
- stateVisible: 当页面打开时,如果有焦点的输入框,自动显示输入法。
- adjustResize:键盘弹出时,Activity 内容会自动上移避免被遮挡。
<activity android:name=".SearchActivity"android:windowSoftInputMode="stateVisible|adjustResize"/>
步骤2 请求textinput焦点
这个可以放在onCreate或onResume都可以。
textInputEditText.requestFocus();
或:
加上
<com.google.android.material.textfield.TextInputEditTextandroid:id="@+id/textview"android:layout_marginTop="30dp"android:layout_width="match_parent"android:layout_height="wrap_content"android:hint="hint" ><requestFocus />
</com.google.android.material.textfield.TextInputEditText>