天天看点

android 解决EditText无法失去焦点和失去焦点后隐藏软键盘的问题

问题:Edittext组件会在界面生成是自动获取焦点,从而软键盘也会自动被调出,

并且点击其他按钮(或空白地方)时,软键盘也不会消失,怎么解决这一现象?

1.解决:在界面生成是自动失去焦点

网友的其他解决方法:

让EditText所在的layout(布局)获得焦点,给layout注册OnTouchListener监听器

直接使用  .requestFocus()   无法获取焦点,焦点依然在EditTtext上

先调用下面这两个方法:

.setFocusable(true);

.setFocusableInTouchMode(true);

再调用  .requestFocus() 就可获取焦点。

relative.setOnTouchListener(new OnTouchListener() {
       public boolean onTouch(View v, MotionEvent event) {
                 // TODO Auto-generated method stub
                    relative.setFocusable(true);
                    relative.setFocusableInTouchMode(true);
                     relative.requestFocus();
                     return false;
            }
 });      

2解决:解决失去焦点隐藏软键盘

如果是Activity,直接重写onTouchEvent方法。代码如下:

 EditText et_username=(EditText)findViewById(R.id.et_username); 

 EditText et_password=(EditText)findViewById(R.id.et_password);

1     @Override
2     public boolean onTouchEvent(MotionEvent event) {
3         InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
4         imm.hideSoftInputFromWindow(et_username.getWindowToken(), 0);
5         imm.hideSoftInputFromWindow(et_password.getWindowToken(), 0);
6         return super.onTouchEvent(event);
7      

如果是fragment,给fragment最外围布局设置了setOnTouchListener监听,达到了预期的效果,代码如下:

 EditText et_username=(EditText)findViewById(R.id.et_username); 

 EditText et_password=(EditText)findViewById(R.id.et_password); 

@Override
    public boolean onTouch(View v, MotionEvent event) {
        InputMethodManager imm = (InputMethodManager) getActivity()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(et_username.getWindowToken(), 0);
        imm.hideSoftInputFromWindow(et_password.getWindowToken(), 0);
        return true;
    }      

查看了一下这个接口和这个方法,文档中对该方法的返回值描述如下:True if the listener has consumed the event, false otherwise。大概意思就是说,如果返回true,则表示监听器消耗了该事件(我的理解就是不用继续向上传递该事件了,该事件的传递到此为止);否则返回false。首先触发到的监听是最底层最直接给它设置的监听,如果是false,并且它的父控件如果也注册次监听,那么它的父控件也会监听也会被触发 ;如果是true,则不会触发父控件的监听。

如果是fragment,给fragment最外围布局设置了setOnTouchListener监听,达到了预期的效果,代码如下:

 EditText et_username=(EditText)findViewById(R.id.et_username); 

 EditText et_password=(EditText)findViewById(R.id.et_password); 

@Override
    public boolean onTouch(View v, MotionEvent event) {
        InputMethodManager imm = (InputMethodManager) getActivity()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(et_username.getWindowToken(), 0);
        imm.hideSoftInputFromWindow(et_password.getWindowToken(), 0);
        return true;
    }