Android 点击空白区域 软键盘消失

来源:互联网 发布:淘宝卖家评价规则 编辑:程序博客网 时间:2024/05/17 22:16

1.之前是这样写的方法

publicvoid closeKeyBoard() {
              InputMethodManagerimm = (InputMethodManager) LoginActivity.this
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
              if(imm.isActive()) {
                     imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
                                   InputMethodManager.HIDE_NOT_ALWAYS);
              }      }

不完美的地方:每次点击空白区域,有键盘的话就消失,没键盘的话就出现,理想状态是,点击空白区域,键盘消失。

 

2.通过给当前界面布局文件的父layout设置点击事件(相当于给整个Activity设置点击事件),在事件里进行键盘隐藏

最终通过该方法实现,点击空白区域键盘消失。

InputMethodManagerimm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

 

3.通过dispatchTouchEvent每次ACTION_DOWN事件中动态判断非EditText本身区域的点击事件,然后在事件中进行屏蔽

@Override
    public booleandispatchTouchEvent(MotionEvent ev) {
       // TODO Auto-generated methodstub
        if (ev.getAction() ==MotionEvent.ACTION_DOWN) {  
               View v= getCurrentFocus();  
               if(isShouldHideInput(v, ev)) {         
                  InputMethodManager imm = (InputMethodManager)        getSystemService(Context.INPUT_METHOD_SERVICE); 
                  if (imm != null) {  
                      imm.hideSoftInputFromWindow(v.getWindowToken(), 0); 
                  }          }  
               returnsuper.dispatchTouchEvent(ev);  
           }  
           // 必不可少,否则所有的组件都不会有TouchEvent了  
           if(getWindow().superDispatchTouchEvent(ev)) {  
               returntrue;  
           }  
                       returnonTouchEvent(ev); 
    }
    public  booleanisShouldHideInput(View v, MotionEvent event) {  
        if (v != null&& (v instanceof EditText)) {  
            int[]leftTop = { 0, 0 };  
            //获取输入框当前的location位置  
           v.getLocationInWindow(leftTop);  
            intleft = leftTop[0];  
            inttop = leftTop[1];  
            intbottom = top + v.getHeight();  
            intright = left + v.getWidth();  
            if(event.getX() > left && event.getX() < right  
                   && event.getY() > top &&event.getY() < bottom) {  
               // 点击的是输入框区域,保留点击EditText的事件  
               return false;  
            } else{  
               return true;  
            } 
        }  
        return false;  
    }  

 


0 0
原创粉丝点击