我知道在android中关闭tyhe键盘的代码是
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
如果我们触摸屏幕中除键盘以外的文本区域之外的区域,谁能建议我隐藏键盘的方法。
最佳答案
关闭软键盘的代码如下:
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
您可以将它放在实用程序类中,或者如果您在 Activity 中定义它,请避免使用 Activity 参数,或调用 hideSoftKeyboard(this)。
您可以编写一个方法来遍历 Activity 中的每个 View ,并检查它是否是 EditText 的实例(如果它没有向该组件注册 setOnTouchListener),一切都会到位。如果您想知道如何做到这一点,其实很简单。这是您要做的,您编写一个递归方法,如下所示。
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();
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);
}
}
}
在 SetcontentView()
之后调用此方法,并将参数作为 View 的 id
,例如:
RelativeLayoutPanel android:id="@+id/parent"> ... </RelativeLayout>
然后调用setupUI(findViewById(R.id.parent))
关于android - 在编辑文本区域外部触摸时隐藏 android 中的键盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20559948/