![](/img/trans.png)
[英]When the soft keyboard appears, it makes my EditText field lose focus
[英]How to lose the focus of a edittext when "done" button in the soft keyboard is pressed?
我的 xml 中有 7 個 edittext 框。我正在使用 OnFocusChangeListener 從 edittext 中讀取值,我正在使用該值進行計算。我想讓我的 edittext 在單擊完成按鈕時失去焦點軟鍵盤。這樣我就可以在編輯文本中獲取值。
從軟鍵盤單擊完成按鈕時,調用EditText
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"
如果有人遇到這個問題,想知道如何在他們的Activity 中一次性取消所有內容的焦點,他們可以將焦點設置在父布局(或任何與此相關的布局)上。
findViewById(R.id.myLayout).requestFocus();
只是更完整的答案
// 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
Kotlin 版本的 ρяσѕρєя K 的回答:
editText.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
editText.clearFocus()
}
false
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.