在android中如何通过点击edittext之外的部分使软键盘隐藏

  我们知道在android中点击edittext框就会自动弹出软键盘,那怎么通过点击edittext之外的部分使软键盘隐藏呢?(微信聊天时的输入框就是这个效果,这个给用户的体验还是很不错的)

  首先我们要先定义一个隐藏软键盘的工具类方法: 

1 public static void hideSoftKeyboard(Activity activity) {
2     InputMethodManager inputMethodManager = (InputMethodManager)  activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
3     inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
4 }

 

    接下来的问题是应该怎么调用这个方法了,我们可以给我们的activity中的每个组件注册一个OnTouchListener监听器,这样只要我们手指接触到了其他组件,就会触发OnTouchListener监听器的onTouch方法,从而调用上面的隐藏软键盘的方法来隐藏软键盘。

  这里还有一个问题就是如果activity中有很多组件怎么办,难不成每个组件都要写代码去注册这个OnTouchListener监听器?大可不必,我们只要找到根布局,然后让根布局自动找到其子组件,再递归注册监听器即可,详见下面代码:

 1 public void setupUI(View view) {
 2         //Set up touch listener for non-text box views to hide keyboard.
 3         if(!(view instanceof EditText)) {
 4             view.setOnTouchListener(new OnTouchListener() {
 5                 public boolean onTouch(View v, MotionEvent event) {
 6                     hideSoftKeyboard(Main.this);  //Main.this是我的activity名
 7                     return false;
 8                 }
 9             });
10         }
11 
12         //If a layout container, iterate over children and seed recursion.
13         if (view instanceof ViewGroup) {
14             for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
15                 View innerView = ((ViewGroup) view).getChildAt(i);
16                 setupUI(innerView);
17             }
18         }
19     }

  总的来说,我们在执行了actvity的oncreateview方法之后就调用setupUI(findViewById(R.id.root_layout))就可以了(其中root_layout为我们的根布局id)。是不是很简单了?:)

  这里要谢过stackoverflow上的大神(本文基本为翻译):http://stackoverflow.com/questions/4165414/how-to-hide-soft-keyboard-on-android-after-clicking-outside-edittext

  建议广大程序员们多用google,中文搜不到要试试英文搜索,比如这篇答案就是我用关键字“android hide keyboard click outside”搜出来的。

posted @ 2014-05-14 22:03  beanmoon  阅读(3798)  评论(1编辑  收藏  举报