![](/img/trans.png)
[英]EditText focus is not working in android studio, i want to hide a textview when focus change in edittext, how to do this?
[英]Hide keyboard after change focus of Edittext in Android
目前我在 Edittext 之間切換時遇到隱藏鍵盤的問題。 我用以下源代碼隱藏了鍵盤:
edittext1.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
edittext1.requestfocus();
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
});
edittext2.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
edittext1.requestfocus();
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
})
但是上面的代碼沒有成功。 每次我觸摸它時,鍵盤都會顯示。 當按住edittext並移出edittext區域時,它仍然顯示鍵盤。
我不知道如何在以下情況下隱藏鍵盤:
在這種情況下你能幫我嗎? 謝謝。
public class CompositeOnChangeFocusListener implements OnFocusChangeListener{
private View currentFocusedView = null;
public void onFocusChange(View v, boolean hasFocus) {
//on a focus change.
if(currentFocusedView != v){
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
//case a view in this composite has focus.
if(hasFocus) {
currentFocusedView = v;
}
//case no view using this composite is focused.
if(v == currentFocusedView && !hasFocus){
currentFocusedView = null;
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}
}
OnFocusChangeListener
的這個實現將跟蹤當前聚焦的View
,如果焦點已經改變,它將移除鍵盤。 它還將根據hasFocused
boolean
更新關注哪個視圖。
OnFocusChangeListener listner = new CompositeOnFocusChangeListener();
//Attach the same exact listener to both.
edittext1.setOnFocusChangeListener(listner);
edittext2.setOnFocusChangeListener(listner);
還嘗試將布局 xml 中的頂級視圖設置為可聚焦,這樣當您滑出EditText
焦點時,應該 go 到頂級視圖而不是粘在EditText
上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.