我在xml中有7个EditText框。我使用OnFocusChangeListener读取edittext的值,并将该值用于计算。我想在软键盘上的完成按钮被点击时使edittext失去焦点,以便我可以获取edittext中的值。
我在xml中有7个EditText框。我使用OnFocusChangeListener读取edittext的值,并将该值用于计算。我想在软键盘上的完成按钮被点击时使edittext失去焦点,以便我可以获取edittext中的值。
当从软键盘上的“完成”按钮点击时,调用EditText
的clearFocus
方法来使其失去焦点。做法如下:
调用EditText
的clearFocus
方法来使其失去焦点,示例代码:
myEditText.clearFocus();
editText.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(actionId==EditorInfo.IME_ACTION_DONE){
//Clear focus here from edittext
editText.clearFocus();
}
return false;
}
});
同时在EditText的xml中添加android:imeOptions="actionDone"
findViewById(R.id.myLayout).requestFocus();
ρяσѕρєя K答案的Kotlin版本:
editText.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
editText.clearFocus()
}
false
}
只是一个更完整的答案
// This will change the ‘RETURN’ button in your the EditText’s soft keyboard to a ‘DONE’ button.
editText.setImeOptions(EditorInfo.IME_ACTION_DONE);
// Use the InputMethodManager to close the soft keyboard
editText.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(actionId==EditorInfo.IME_ACTION_DONE){
//Clear focus here from edittext
InputMethodManager imm = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
return false;
}
});
Kotlin,它对我有用:
main.clearFocus()
main 是一个根 ConstraintLayout
android:imeOptions="actionSend"
不会清除焦点,即使您调用editText.clearFocus();
请确保使用android:imeOptions="actionDone"
。 - Esdras Lopez