Android editText点击空白处隐藏键盘

方法一: 通过给当前界面布局文件的父layout设置点击事件,在点击事件里隐藏键盘
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/traceroute_rootview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/white"
    android:clickable="true"
    android:gravity="center_horizontal"
    android:orientation="vertical" >

</LinearLayout>

加上id和clickable=true

然后在点击事件里

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);  
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
方法二:通过dispatchTouchEvent每次ACTION_DOWN事件中动态判断非EditText本身区域的点击事件,然后在事件中进行屏蔽。
@Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少,否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域,保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }
解决思路与iOS中的事件分发机制是类似,对于处理隐藏事件比较清晰,通过层层事件分发,然后判断是否在需要屏蔽的区域。

猜你喜欢

转载自blog.csdn.net/pxcz110112/article/details/80360620
今日推荐