我們知道在android中點擊edittext框就會自動彈出軟鍵盤,那怎么通過點擊edittext之外的部分使軟鍵盤隱藏呢?(微信聊天時的輸入框就是這個效果,這個給用戶的體驗還是很不錯的)
首先我們要先定義一個隱藏軟鍵盤的工具類方法:
1 public static void hideSoftKeyboard(Activity activity) { 2 InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE); 3 inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0); 4 }
接下來的問題是應該怎么調用這個方法了,我們可以給我們的activity中的每個組件注冊一個OnTouchListener監聽器,這樣只要我們手指接觸到了其他組件,就會觸發OnTouchListener監聽器的onTouch方法,從而調用上面的隱藏軟鍵盤的方法來隱藏軟鍵盤。
這里還有一個問題就是如果activity中有很多組件怎么辦,難不成每個組件都要寫代碼去注冊這個OnTouchListener監聽器?大可不必,我們只要找到根布局,然后讓根布局自動找到其子組件,再遞歸注冊監聽器即可,詳見下面代碼:
1 public void setupUI(View view) { 2 //Set up touch listener for non-text box views to hide keyboard. 3 if(!(view instanceof EditText)) { 4 view.setOnTouchListener(new OnTouchListener() { 5 public boolean onTouch(View v, MotionEvent event) { 6 hideSoftKeyboard(Main.this); //Main.this是我的activity名 7 return false; 8 } 9 }); 10 } 11 12 //If a layout container, iterate over children and seed recursion. 13 if (view instanceof ViewGroup) { 14 for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) { 15 View innerView = ((ViewGroup) view).getChildAt(i); 16 setupUI(innerView); 17 } 18 } 19 }
總的來說,我們在執行了actvity的oncreateview方法之后就調用setupUI(findViewById(R.id.root_layout))就可以了(其中root_layout為我們的根布局id)。是不是很簡單了?:)
這里要謝過stackoverflow上的大神(本文基本為翻譯):http://stackoverflow.com/questions/4165414/how-to-hide-soft-keyboard-on-android-after-clicking-outside-edittext
建議廣大程序員們多用google,中文搜不到要試試英文搜索,比如這篇答案就是我用關鍵字“android hide keyboard click outside”搜出來的。