在做项目中就遇到了这个问题,就是需要当点击页面其他部位时,输入键盘消失,当点击到EditTex时,不进行操作。下面是我的解决方案,实现Activity的dispatchTouchEvent方法,对事件进行触摸事件进行监听。
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
//如果点击除EditText以外的其他VIew,键盘回收
if (v instanceof EditText) {
View nextFocus = findViewFocus(contentView,event);
if(nextFocus != null && nextFocus instanceof EditText){
return super.dispatchTouchEvent( event );
}
Rect outRect = new Rect();
v.getGlobalVisibleRect(outRect);
if (!outRect.contains((int)event.getRawX(), (int)event.getRawY())) {
//AndroidUtils.hideSoftKeyboard(this,contentView);
contentView.requestFocus();
v.clearFocus();
}
}
}
return super.dispatchTouchEvent( event );
}
private View findViewFocus(ViewGroup viewGroup,MotionEvent event){
View view = null;
int childCount = viewGroup.getChildCount();
for(int i = 0;i< childCount ;i++ ){
view = viewGroup.getChildAt(i);
Rect outRect = new Rect();
view.getGlobalVisibleRect(outRect);
if (outRect.contains((int)event.getRawX(), (int)event.getRawY())) {
if(view instanceof ViewGroup){
return findViewFocus((ViewGroup) view,event);
} else {
return view;
}
}
}
return null;
}
网友评论