Android中点击隐藏软键盘最佳方法
实现功能:点击EditText,软键盘出现并且不会隐藏,点击或者触摸EditText以外的其他任何区域,软键盘被隐藏;
1、重写dispatchTouchEvent()方法,获取当前触摸事件为DOWN的时候隐藏软键盘
@Override
publicbooleandispatchTouchEvent(MotionEventev){
//Fingertouchscreenevent
if(ev.getAction()==MotionEvent.ACTION_DOWN){
//getcurrentfocus,GenerallyitisEditText
Viewview=getCurrentFocus();
if(isShouldHideSoftKeyBoard(view,ev)){
hideSoftKeyBoard(view.getWindowToken());
}
}
returnsuper.dispatchTouchEvent(ev);
}
2、isShouldHideInput()方法;
/**
*Judgewhatsituationhidethesoftkeyboard,clickEditTextviewshouldshowsoftkeyboard
*@paramvIncidentevent
*@paramevent
*@return
*/
privatebooleanisShouldHideSoftKeyBoard(Viewview,MotionEventevent){
if(view!=null&&(viewinstanceofEditText)){
int[]l={0,0};
view.getLocationInWindow(l);
intleft=l[0],top=l[1],bottom=top+view.getHeight(),right=left
+view.getWidth();
if(event.getX()>left&&event.getX()<right
&&event.getY()>top&&event.getY()<bottom){
//IfclicktheEditTextevent,ignoreit
returnfalse;
}else{
returntrue;
}
}
//ifthefocusisEditText,ignoreit;
returnfalse;
}
3、hideSoftKeyBoard()方法;
/**
*hidesoftkeyboard
*@paramtoken
*/
privatevoidhideSoftKeyBoard(IBindertoken){
if(token!=null){
InputMethodManagerim=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(token,
InputMethodManager.HIDE_NOT_ALWAYS);
}
}
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持毛票票!
热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短