我有一个名为 myTextview
的 EditText
。我希望软键盘在我单击 EditText
时显示,但如果我在 EditText
之外单击则关闭。所以我使用下面的方法。但是当我在 View 外部单击时键盘不会关闭(我单击 TextView
)。如何修复此代码?
myTextview.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
} else {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myTextview.getWindowToken(), 0);
}
}
});
最佳答案
我找到了更好的解决方案:
覆盖 Activity 中的 dispatchTouchEvent
方法。
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
View v = getCurrentFocus();
if (v != null && (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE) &&
v instanceof EditText &&
!v.getClass().getName().startsWith("android.webkit.")) {
int[] sourceCoordinates = new int[2];
v.getLocationOnScreen(sourceCoordinates);
float x = ev.getRawX() + v.getLeft() - sourceCoordinates[0];
float y = ev.getRawY() + v.getTop() - sourceCoordinates[1];
if (x < v.getLeft() || x > v.getRight() || y < v.getTop() || y > v.getBottom()) {
hideKeyboard(this);
}
}
return super.dispatchTouchEvent(ev);
}
private void hideKeyboard(Activity activity) {
if (activity != null && activity.getWindow() != null) {
activity.getWindow().getDecorView();
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0);
}
}
}
即使您正在使用 webview,这也适用。
2020 年 7 月 10 日更新
上述方法效果很好,但 EditText 仍然有焦点,打字光标仍然可见。
解决上述问题。这样做
添加
findViewById(android.R.id.content).setFocusableInTouchMode(true);
在你的 onCreate() 方法中添加
findViewById(android.R.id.content).clearFocus();
在hideKeyboard()
方法
关于android - 在Android中单击EditText外部时关闭键盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20713273/