很奇怪,我在给EditText设置setOnFocusChangeListener()监听,但是始终未能成功,焦点一直存在,不知其原因,,代码如下:
1 et_password.setOnFocusChangeListener(new OnFocusChangeListener() { 2 3 @Override 4 public void onFocusChange(View v, boolean hasFocus) { 5 if (hasFocus) { 6 InputMethodManager imm = (InputMethodManager) getActivity() 7 .getSystemService(Context.INPUT_METHOD_SERVICE); 8 imm.hideSoftInputFromWindow(et_username.getWindowToken(), 0); 9 } 10 11 } 12 });
后来各种百度,最后给fragment设置了setOnTouchListener(this)监听,达到了预期的效果,代码如下:
@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:
到Android Developers上查看了一下这个接口和这个方法,文档中对该方法的返回值描述如下:True if the listener has consumed the event, false otherwise。大概意思就是说,如果返回true,则表示监听器消耗了该事件(我的理解就是不用继续向上传递该事件了,该事件的传递到此为止);否则返回false。首先触发到的监听是最底层最直接给它设置的监听,如果是false,并且它的父控件如果也注册次监听,那么它的父控件也会监听也会被触发 ;如果是true,则不会触发父控件的监听。
如果是Activity,直接重写onTouchEvent方法。代码如下:
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 8 }
EditText失去焦点隐藏软键盘,布布扣,bubuko.com
原文:http://www.cnblogs.com/ws5861/p/3591195.html