需求:在点击某个Edittext下面的空白位置,则软键盘隐藏
代码:
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
new GetIput_height().execute("");
View v = getCurrentFocus();
int pointY=(int) ev.getRawY();//手指点击的Y
int[] locationTheme = new int[2];
posting_post_details.getLocationOnScreen(locationTheme);//从屏幕顶端算起,也就是包括了通知栏的高度
int themeY = locationTheme[1]+posting_post_details.getHeight();//edittext的Y
int[] locationReply = new int[2];
reply_face_linear.getLocationOnScreen(locationReply);
int reply_face_linearY = locationReply[1];//软键盘的y
if(pointY<reply_face_linearY && pointY>themeY){
if (imm != null) {
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
PostingAddFaceRelativeLayout.view.setVisibility(View.GONE);
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN|WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
PostingAddFaceRelativeLayout.btn_face.setBackgroundResource(R.drawable.mess_gray);
}
}
return super.dispatchTouchEvent(ev);
}
// 必不可少,否则所有的组件都不会有TouchEvent了
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return false;
}
其中:
ev.getRawY():这个高度包括状态栏,相对这个屏幕
posting_post_details.getLocationOnScreen(locationTheme):也是相对整个屏幕
pointY<reply_face_linearY && pointY>themeY:手指点击的位置比软键盘的低,比EditText来的高
位置从:左上角开始算起(x,y) 越是往下,往右 ,y,x 越大~
图片解析:
setFocusable这个是用键盘是否能获得焦点
setFocusableInTouchMode这个是触摸是否能获得焦点
博主 炸斯特介绍 android之View坐标系(view获取自身坐标的方法和点击事件中坐标的获取)很清晰:
还画了图:http://blog.youkuaiyun.com/jason0539/article/details/42743531