問題描述
我只想在edittext"外部單擊時自動失去焦點并隱藏鍵盤.目前,如果我點擊edittext"它會聚焦,但我需要點擊后退按鈕才能取消聚焦.
I just want when click outside the "edittext" to automatically lose focus and hide keyboard. At the moment, if I click on the "edittext" it focuses but i need to hit the back button to unfocus.
推薦答案
要解決這個問題,首先要使用 Edittext 的 setOnFocusChangeListener
To solve this problem what you have to do is first use setOnFocusChangeListener of that Edittext
edittext.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
Log.d("focus", "focus lost");
// Do whatever you want here
} else {
Log.d("focus", "focused");
}
}
});
然后您需要做的是在包含 Edittext 的活動中覆蓋 dispatchTouchEvent,請參見下面的代碼
and then what you need to do is override dispatchTouchEvent in the activity which contains that Edittext see below code
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if ( v instanceof EditText) {
Rect outRect = new Rect();
v.getGlobalVisibleRect(outRect);
if (!outRect.contains((int)event.getRawX(), (int)event.getRawY())) {
Log.d("focus", "touchevent");
v.clearFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
}
return super.dispatchTouchEvent(event);
}
現在會發生什么,當用戶點擊外部時,首先會調用這個 dispatchTouchEvent,然后從 editext 清除焦點,現在你的 OnFocusChangeListener 將被調用,焦點已經改變,現在你可以做任何你想做的事情想做,希望有效:)
Now what will happen is when a user click outside then, firstly this dispatchTouchEvent will get called which then will clear focus from the editext, now your OnFocusChangeListener will get called that focus has been changed, now here you can do anything which you wanted to do, hope it works :)
這篇關于點擊外部edittext失去焦點的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!