xml
<EditText
android:id="@+id/et_test"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入内容"
android:imeOptions="actionDone" />
- 在 Android 开发中,上述代码中,EditText 控件的
android:imeOptions="actionDone"属性不生效,即无法实现点击软键盘上的"完成"按钮时
问题原因
-
android:imeOptions="actionDone"属性用于将软键盘右下角的回车按钮变为"完成"按钮,目的是为了隐藏软键盘 -
根本原因是未设置单行输入,系统优先允许换行,但也可以监听此动作执行自定义操作
处理方法
- 使用
android:inputType="text"属性,设置为单行输入
xml
<EditText
android:id="@+id/et_test"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入内容"
android:imeOptions="actionDone"
android:inputType="text" />
- 或者,使用监听器监听此动作执行自定义操作
xml
<EditText
android:id="@+id/et_test"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入内容"
android:imeOptions="actionDone" />
java
EditText etTest = findViewById(R.id.et_test);
etTest.setOnEditorActionListener((v, actionId, event) -> {
Log.i(TAG, "actionId: " + actionId);
if (actionId == EditorInfo.IME_ACTION_DONE) {
// 隐藏软键盘
hideKeyboard();
// 清除焦点
v.clearFocus();
// 表示监听器已经处理这个事件,系统不需要再处理
return true;
}
// 针对某些输入法的情况
if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
if (event != null && event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
hideKeyboard();
v.clearFocus();
return true;
}
}
return false;
});
java
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);