Recently there is a need to pop the soft keyboard when you click EditText, and then hide the soft keyboard when you click on an empty space or another control. This requirement is very useful on tablets, because the screen is large and users cannot hide at the bottom left corner every time, and it's easier to click in the blanks.
Just beginning to search from the Internet, not very ideal, then suddenly think of the Android event distribution mechanism, and then think of the implementation method:
PublicclasshomeactivityextendsActivity{
......
@Override
PublicBooleandispatchtouchevent(motioneventEV){
if(EV.getaction()==motionevent.Action_down){
//Get the currently focused view, usually the EditText (special case is the trajectory or the entity case will move the focus)
Viewv=Getcurrentfocus();
if(Isshouldhideinput(v,EV)){
Hidesoftinput(v.Getwindowtoken());
}
}
returnSuper.dispatchtouchevent(EV);
}
/**
* Determine if the keyboard is hidden based on the relative ratio of the coordinates of the edittext and the user's clicked coordinates, because there is no need to hide when the user clicks EditText
*
* @param v
* @param event
* @return
*/
PrivateBooleanIsshouldhideinput(Viewv,motioneventEvent){
if(v!=NULL&&(vinstanceofEditText)){
int[]L={0,0};
v.Getlocationinwindow(L);
int Left=L[0],Top=L[1],Bottom=Top+v.getheight(), Right= Left
+v.getwidth();
if(Event.GetX()> Left&&Event.GetX()< Right
&&Event.GetY()>Top&&Event.GetY()<Bottom){
//Click on the EditText event to ignore it.
returnfalse;
}Else{
returntrue;
}
}
//If the focus is not edittext then ignore, this occurs when the view has just been drawn, the first focus is not on the EditView, and the user uses the trackball to select other focus
returnfalse;
}
/**
* One of a variety of hidden software disk methods
*
* @param token
*/
PrivatevoidHidesoftinput(IBindertoken){
if(token!=NULL){
Inputmethodmanagerim=(Inputmethodmanager)Getsystemservice(Context.Input_method_service);
im.Hidesoftinputfromwindow(token,
Inputmethodmanager.hide_not_always);
}
}
......
}
The following explanation of the code, the first method to achieve the activity of the Dispatchtouchevent method, in fact, not necessarily acitivty,3.0 fragment can also, the main purpose is to intercept user touch events. Specific Android event distribution mechanism see my other blog:http://www.cnblogs.com/coding-way/archive/2012/07/04/2575769.html
Now, when the user touches, dispatchtouchevent will be called, then the method has a more detailed comment, no longer repeat.
Original link: http://www.cnblogs.com/coding-way/archive/2012/07/10/2585511.html