二話不說(shuō)赖瞒,來(lái),直接上效果
第一步監(jiān)聽(tīng)Activity的dispatchTouchEvent和onTouchEvent事件,在有的手機(jī)里面onTouchEvent不會(huì)觸發(fā)领铐,保險(xiǎn)起見(jiàn),這兩個(gè)方法都加上劈狐,另外特別注意的是罐孝,這個(gè)兩個(gè)事件的監(jiān)聽(tīng)可以寫(xiě)在BaseActivity中!
代碼如下:
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
hideSolftKeyboard(event);
return super.dispatchTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
hideSolftKeyboard(event);
return super.onTouchEvent(event);
}
/**
* 隱藏鍵盤(pán)
*/
public void hideSolftKeyboard(MotionEvent event){
try{
if(event.getAction() == MotionEvent.ACTION_DOWN){
View focusView = getCurrentFocus();
//除了點(diǎn)擊EidtText自身區(qū)域的其他任何區(qū)域肥缔,都將鍵盤(pán)收起
if(null != focusView && null != focusView.getWindowToken() && !ViewUtils.isTouchView(event, focusView)){
SolftInputUtil.hideSoftInputFromWindow(this);
}
}
}catch (Exception e){
e.printStackTrace();
}
}
到這里代碼就寫(xiě)完了莲兢,另外需要補(bǔ)充下輔助代碼段
1.ViewUtils.isTouchView:判斷當(dāng)前觸摸的是不是當(dāng)前獲取焦點(diǎn)的EditText
2.SolftInputUtil.hideSoftInputFromWindow:隱藏鍵盤(pán)
/**
* 是否觸摸了當(dāng)前焦點(diǎn)控件
* @param event
* @param focusView
* @return
*/
public static boolean isTouchView(MotionEvent event, View focusView){
if(null == event || null == focusView){
return false;
}
float x = event.getX();
float y = event.getY();
int[] outLocation = new int[2];
focusView.getLocationOnScreen(outLocation);
RectF rectF = new RectF(outLocation[0], outLocation[1] ,outLocation[0] + focusView.getWidth() ,outLocation[1] + focusView.getHeight());
if(x >= rectF.left && x <= rectF.right && y >= rectF.top && y <= rectF.bottom){
return true;
}
return false;
}
/**
* 隱藏Activity里面獲得焦點(diǎn)的View的軟鍵盤(pán)
*
* @param activity
*/
public static void hideSoftInputFromWindow(Activity activity) {
InputMethodManager parentImm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (parentImm.isActive()) {
View view = activity.getCurrentFocus();
if (null != view) {
parentImm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
代碼隨簡(jiǎn)單,希望也能幫到一部分朋友們续膳。