Android实现点击空白处回收键盘

1点击空白回收键盘的思路

首先肯定要判断出点击屏幕的位置是不是空白处,如果不是空白处则不需要进行键盘的收回
1如何判断是空白处还是输入框?需要监听一下触摸的位置,如果触摸的位置在输入框内,则不需要进行回收。否则如果触摸的位置在输入框之外,则需要进行键盘回收

public static boolean isShouldHideKeyBord(View v, MotionEvent ev) {
    
    
        if (v != null && (v instanceof EditText)) {
    
    
            int[] l = {
    
    0, 0};
            //获取到当前窗口的父窗口坐标
            v.getLocationInWindow(l);
            int left = l[0];
            int top = l[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            return !(ev.getX() > left && ev.getX() < right && ev.getY() > top && ev.getY() < bottom);
        }
        return false;
    }

2如何进行回收键盘,如下

public static void hintKeyBoards(View view) {
    
    
        InputMethodManager manager = ((InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE));
        if (manager != null) {
    
    
            manager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

总结:将以上两个步骤封装到一个工具类中,使用时直接加到相应的界面即可

public class KeyboardUtils {
    
    
    //展示键盘的方法
    public static void showKeyboard(View view) {
    
    
        InputMethodManager imm = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
    
    
            view.requestFocus();
            imm.showSoftInput(view, 0);
        }
    }

    /**
     * 隐藏软键盘
     * @param view
     */
    public static void hintKeyBoards(View view) {
    
    
        InputMethodManager manager = ((InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE));
        if (manager != null) {
    
    
            manager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**
     * 判定当前是否需要隐藏
     */
    public static boolean isShouldHideKeyBord(View v, MotionEvent ev) {
    
    
        if (v != null && (v instanceof EditText)) {
    
    
            int[] l = {
    
    0, 0};
            //获取到当前窗口的父窗口坐标
            v.getLocationInWindow(l);
            int left = l[0];
            int top = l[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            return !(ev.getX() > left && ev.getX() < right && ev.getY() > top && ev.getY() < bottom);
        }
        return false;
    }
}

2Kotlin使用方法,直接在需要的界面中加入以下方法即可

		@CallSuper
        override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
    
    
                if (ev.action == MotionEvent.ACTION_DOWN) {
    
    
                        val view = currentFocus
                        //打印出x和y的坐标位置
                        if (KeyboardUtils.isShouldHideKeyBord(view, ev)) {
    
    
                                KeyboardUtils.hintKeyBoards(view)
                        }
                }
                return super.dispatchTouchEvent(ev)
        }

猜你喜欢

转载自blog.csdn.net/m0_56184347/article/details/125608407
今日推荐