最近做项目要求实现当点击edittext之外的view时,键盘收起的功能。google了一大堆,也没有什么思路,无奈自己写了一个。
实现原理很简单:
1.dispatchTouchEvent中获取点击事件坐标
2.根据坐标找到子view,判断子view,
a.为空说明点击了空白处,收起键盘
b.不为空,判断view是不是edittext,如果不是,收起键盘
代码:
public class EditFocusLayout extends LinearLayout {
private final static String TAG = "EditFocusLayout";
private Context mContext;
public EditFocusLayout(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
int x = (int) ev.getX();
int y = (int) ev.getY();
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
View targetView = getTouchTargetView(this, x, y);
InputMethodManager imm = (InputMethodManager)mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
if (targetView == null) {//为空直接收起键盘
imm.hideSoftInputFromWindow(this.getWindowToken(), 0);
} else if (!(targetView instanceof EditText)){//不为edittext也收起键盘
imm.hideSoftInputFromWindow(targetView.getWindowToken(), 0);
}
}
return super.dispatchTouchEvent(ev);
}
/**
* 获取点击到的view
* @param viewGroup
* @param x
* @param y
* @return
*/
private View getTouchTargetView(ViewGroup viewGroup, int x, int y) {
View touchView = null;
for (int i = 0; i < viewGroup.getChildCount(); i ++) {
View view = viewGroup.getChildAt(i);
if (view instanceof ViewGroup) {
View tempView = getTouchTargetView((ViewGroup) view, x, y);
if (tempView != null) touchView = tempView;
} else {
if (isTouchPointInView(view, x, y)) touchView = view;
}
}
return touchView;
}
private boolean isTouchPointInView(View view, int x, int y) {
Rect rect = new Rect(view.getLeft(), view.getTop(), view.getRight(), view.getBottom());
return rect.contains(x, y);
}
}
源码