在android中如何通過點擊edittext之外的部分使軟鍵盤隱藏

來源:互聯網
上載者:User

標籤:android   des   style   blog   class   code   

  我們知道在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”搜出來的。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.