[英]Android: Hiding soft keyboard when touching out of EditText
這是操作系統行為在按下“后退”按鈕或“完成”按鈕時隱藏softInputKeyboard,我想在用戶單擊EditText時隱藏鍵盤。 因此,我創建了一個BaseActivity,並在其中編寫了以下代碼。
public class BaseActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
boolean handleReturn = super.dispatchTouchEvent(ev);
View view = getCurrentFocus();
int x = (int) ev.getX();
int y = (int) ev.getY();
if (view instanceof EditText) {
EditText innerView = (EditText) getCurrentFocus();
if (ev.getAction() == MotionEvent.ACTION_UP &&
!getLocationOnScreen(innerView).contains(x, y)) {
InputMethodManager input = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
input.hideSoftInputFromWindow(getWindow().getCurrentFocus()
.getWindowToken(), 0);
}
}
return handleReturn;
}
protected Rect getLocationOnScreen(EditText mEditText) {
Rect rect = new Rect();
int[] location = new int[2];
mEditText.getLocationOnScreen(location);
rect.left = location[0];
rect.top = location[1];
rect.right = location[0] + mEditText.getWidth();
rect.bottom = location[1] + mEditText.getHeight();
return rect;
}
}
為MyActivity擴展了上述類,並且在其布局上對EditTexts可以正常工作。 但是,當我彈出帶有自定義布局的AlertDialog時,它不起作用,其中包含許多EditText。
我從AlertDialog甚至是Dialog的前景中觸摸了EditText,但鍵盤沒有關閉。
在這種情況下如何隱藏呢?
使用以下代碼。 這個對我有用
@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())) {
v.clearFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
}
return super.dispatchTouchEvent(event);
}
要實現這一目標,需要記住兩件事-
假設xml結構像
<ViewGroup focusable=true focusInTouchMode=true>
<EditText />
</ViewGroup>
在onfocuschangelistener()
上設置onfocuschangelistener()
,即
edittext.editCaption.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0); } });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.