// Check if no view has focus: Viewview=this.getCurrentFocus(); if (view != null) { InputMethodManagerimm= (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); }
2. 封装为静态工具方法
为了方便在不同的Activity中使用,可以将上述代码封装为静态工具方法。
1 2 3 4 5 6 7 8 9 10
publicstaticvoidhideKeyboard(Activity activity) { InputMethodManagerimm= (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE); //Find the currently focused view, so we can grab the correct window token from it. Viewview= activity.getCurrentFocus(); //If no view currently has focus, create a new one, just so we can grab a window token from it if (view == null) { view = newView(activity); } imm.hideSoftInputFromWindow(view.getWindowToken(), 0); }