1、页面启动键盘自动显示或隐藏
getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
2、点击非编辑区域隐藏键盘
@Override public boolean dispatchTouchEvent(MotionEvent event) { //点击非编辑区域隐藏输入法 if (event.getAction() == MotionEvent.ACTION_DOWN) { View v = getCurrentFocus(); if (v instanceof EditText) { Rect outRect = new Rect(); v.getGlobalVisibleRect(outRect); if (!outRect.contains((int) event.getRawX(), (int) event.getRawY())) { v.clearFocus(); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(v.getWindowToken(), 0); } } } return super.dispatchTouchEvent(event); }
3、手动调用及隐藏键盘
/** * 开启软键盘 */ public static void openSoftKeyboard(EditText et) { InputMethodManager inputManager = (InputMethodManager) et.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.showSoftInput(et, InputMethodManager.SHOW_FORCED);//显示 // inputManager.showSoftInput(et, 0);//隐藏 } /** * 关闭软键盘 */ public static void closeSoftKeyboard(Activity context) { InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); if (inputMethodManager != null && context.getCurrentFocus() != null) { inputMethodManager.hideSoftInputFromWindow(context.getCurrentFocus() .getWindowToken(), 0); } }
4、当Dialog中存在EditText时,往往无法实现Dialog显示后自动调用键盘,这是因为的实现需要通过Handler,我们直接调用键盘显示往往会快过dialog显示,布局尚未完成则键盘也不会出现,所以我们需要一个延时来调用键盘
@Override public void show() { super.show(); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { showKeyboard(); } }, 200); } public void showKeyboard() { InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS); }