我想通过触摸背景或线性布局来隐藏软键盘。 我该怎么办?
任何人都可以帮助我吗? 请
答案 0 :(得分:1)
您可以在根视图的onClick
事件中隐藏软键盘
linearLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
}
});
答案 1 :(得分:1)
尝试使用onTouchEvent
@Override
public boolean onTouchEvent(MotionEvent event) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.
INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
答案 2 :(得分:1)
根据H Raval的建议,this是最佳解决方案。
答案中的函数setupUI
将遍历您的ViewGroup
并将onTouch
侦听器添加到除EditText
之外的所有其他视图,这是调用隐藏键盘的代码的正确方法。< / p>
代码: -
public void setupUI(View view) {
//Set up touch listener for non-text box views to hide keyboard.
if(!(view instanceof EditText)) {
view.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
hideSoftKeyboard(MyActivity.this);
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);
}
}
}
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}