方法一:
重写dispatchTouchEvent,判断点击EditText之外则隐藏输入框。
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
//获取activity中获取焦点的view
View view = getCurrentFocus();
if (isShouldHideInput(view, ev)) {
hideInput(view);
}
return super.dispatchTouchEvent(ev);
}
// 必不可少,否则所有的组件都不会有TouchEvent了
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
private void hideInput(View view) {
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
}
public boolean isShouldHideInput(View view, MotionEvent event) {
if (view != null && (view instanceof EditText)) {
int[] leftAndTop = {0, 0};
//获取输入框当前的location位置,相对于父窗口里的坐标
view.getLocationInWindow(leftAndTop);
int left = leftAndTop[0];
int top = leftAndTop[1];
int bottom = top + view.getHeight();
int right = left + view.getWidth();
if (event.getX() > left && event.getX() < right &&
event.getY() > top && event.getY() < bottom) {
// 点击的是输入框区域,保留点击EditText的事件
return false;
} else {
return true;
}
}
return false;
}
方法二:
根布局添加clickable属性,设置点击事件隐藏输入框即可。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rootview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true">
//....
</RelativeLayout>
mRootView = ((RelativeLayout) this.findViewById(R.id.rootview));
mRootView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
});
参考:Android点击EditText文本框之外任何地方隐藏键盘的解决办法
android点击屏幕上EditText区域以外的任何地方隐藏键盘的方法
getLocationInWindow与getLocationOnScreen区别:
View.getLocationInWindow(int[] location)
一个控件在其父窗口中的坐标位置
获取在当前窗口内的绝对坐标,getLeft , getTop, getBottom, getRight, 这一组是获取相对在它父窗口里的坐标。
start = (Button) findViewById(R.id.start);
int []location=new int[2];
start.getLocationOnScreen(location);
int x=location[0];//获取当前位置的横坐标
int y=location[1];//获取当前位置的纵坐标
View.getLocationOnScreen(int[] location)
一个控件在其整个屏幕上的坐标位置
获取在整个屏幕内的绝对坐标,注意这个值是要从屏幕顶端算起,也就是包括了通知栏的高度。
start = (Button) findViewById(R.id.start);
int []location=new int[2];
start.getLocationInWindow(location);
int x=location[0];//获取当前位置的横坐标
int y=location[1];//获取当前位置的纵坐标