一、自动隐藏软键盘
在Android中,只要点击EditText及其子类,软键盘都会自动弹出,但是让人不解的是,点击非EditText及其子类的控件后,软键盘是不会自动隐藏的。
所以,我们就需要在Activity中解决这个问题。
二、替换Fragment后软键盘无法弹出的问题
1. 在容器中添加一个Fragment
2. 调用FragmentTransaction的replace方法替换一个包含EditText的Fragment, 点击EditText软键盘是不会弹出的
三、解决方法:
1 @Override 2 public boolean dispatchTouchEvent(MotionEvent ev) { 3 if (isAutoHideSoftInput()) { 4 View currentFocus = getCurrentFocus(); 5 if (currentFocus != null && currentFocus instanceof EditText) { 6 InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); 7 if (imm.isActive()) { 8 switch (ev.getAction()) { 9 case MotionEvent.ACTION_DOWN: 10 currentFocus.setTag(R.id.ids_auto_hide_softinput_value, true); 11 if (!Boolean.TRUE.equals(currentFocus.getTag(R.id.ids_auto_hide_softinput_listener))) { 12 currentFocus.setOnTouchListener(new OnTouchListener() { 13 @Override 14 public boolean onTouch(View v, MotionEvent event) { 15 if (event.getAction() == MotionEvent.ACTION_DOWN) { 16 v.setTag(R.id.ids_auto_hide_softinput_value, false); 17 v.clearFocus(); // 解决替换Fragment后软键盘无法弹出的问题 18 v.requestFocus(); 19 } 20 return false; 21 } 22 }); 23 currentFocus.setTag(R.id.ids_auto_hide_softinput_listener, true); 24 } 25 break; 26 case MotionEvent.ACTION_UP: 27 if (Boolean.TRUE.equals(currentFocus.getTag(R.id.ids_auto_hide_softinput_value))) { 28 imm.hideSoftInputFromWindow(currentFocus.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); 29 currentFocus.setTag(R.id.ids_auto_hide_softinput_value, false); 30 } 31 break; 32 } 33 } 34 } 35 } 36 return super.dispatchTouchEvent(ev); 37 }