我在类似的问题上尝试了多个答案并遇到了麻烦,我是初学者。现在我正在尝试下面粗体显示的答案:我不熟悉这个人通过创建BaseActivity和编写全局代码的含义。 我刚刚发现了另一种方法,如果我们不想将任何EditText作为输入,并希望在用户触摸EditText以外的任何其他地方时隐藏整个应用程序中的键盘。然后你必须创建一个BaseActivity并编写隐藏键盘的全局代码,如下所示
@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){
View innerView = 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;
}
答案 0 :(得分:1)
我从堆栈溢出用户那里找到了这个方法,它运行正常
在您的活动中
setupUI(findViewById(R.id.activity_id),this);
静态助手类
public static void setupUI(View view, final Activity activity) {
// Set up touch listener for non-text box views to hide keyboard.
if (!(view instanceof EditText)) {
view.setOnTouchListener(new EditText.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
hideSoftKeyboard(activity);
return false;
}
});
}
//If a layout container, iterate over children and seed recursion.
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
View innerView = ((ViewGroup) view).getChildAt(i);
setupUI(innerView, activity);
}
}
}
private static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager =
(InputMethodManager) activity.getSystemService(
Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(
activity.getCurrentFocus().getWindowToken(), 0);
}