We know that clicking on the EditText box in Android will automatically eject the soft keyboard, so how can you hide the soft keyboard by clicking outside the EditText? (The input box in the chat is the effect, the user's experience is very good)
First we need to define a tool class method that hides the soft keyboard:
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 }
The next question is how to call this method, and we can register a Ontouchlistener listener for each component in our activity, so that as long as we touch the other components with our fingers, The Ontouchlistener listener's Ontouch method is triggered to invoke the Hide soft keyboard method above to hide the soft keyboard.
Another problem here is that if there are many components to do in the activity, it is difficult to write code to register the Ontouchlistener listener for each component. It doesn't have to be, we just have to find the root layout, then let the root layout automatically find its subcomponents, and then recursively register the listener, see the following code:
1 Public voidsetupui (view view) {2 //Set up Touch listener for non-text box views to hide keyboard.3 if(! (ViewinstanceofEditText)) {4View.setontouchlistener (NewOntouchlistener () {5 Public BooleanOnTouch (View V, motionevent event) {6Hidesoftkeyboard (Main. This); Main.this is my activity name.7 return false;8 }9 });Ten } One A //If A layout container, iterate over children and seed recursion. - if(ViewinstanceofViewGroup) { - for(inti = 0; I < ((viewgroup) view). Getchildcount (); i++) { theView Innerview =( (ViewGroup) view). Getchildat (i); - setupui (Innerview); - } - } +}
In general, we call SETUPUI (Findviewbyid (r.id.root_layout)) after executing the Actvity Oncreateview method (where root_layout is our root layout id). Isn't it easy? :)
Here to thank the StackOverflow on the Great God (this article is basically translated): http://stackoverflow.com/questions/4165414/ How-to-hide-soft-keyboard-on-android-after-clicking-outside-edittext
Suggest that the vast number of programmers use Google, Chinese search to try English , such as this answer is I use the keyword "android hide keyboard click outside" Search out.