Android 点击空白或滑动时候关闭软键盘(有scrollview的坑) 参考 使用

参考

1、Android打开关闭软键盘
2、android 滑动或者点击其他地方隐藏键盘的方法
3、android中ScrollView的setOnClickListener无效

使用

1、SomeActivity extends BaseActivity
//父控件resid,如果有scrollview是子控件但是match_parent的话用scrollview的resid
hideParentSoftKeyborad(R.id.sv_batch_review);
2、BaseActivity
/**
     * 点击空白处或滑动时候隐藏软键盘
     * parent里面下如果有scrollview占据整个画面的话,必须resLayout=scrollview_resid,不然监听不到
     * */
    protected void hideParentSoftKeyborad(int resLayout){
        //以前的:点空白处隐藏软键盘
//        findViewById(resLayout).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                LogUtil.d("===hideParentSoftKeyborad = onClick");
//                AppUtil.hideSoftKeyboard(instance);
//            }
//        });

        findViewById(resLayout).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        AppUtil.hideSoftKeyboard(instance);
                        break;
                    case MotionEvent.ACTION_MOVE:
                        AppUtil.hideSoftKeyboard(instance);
                        break;
                }
                return false;
            }
        });
    }
3、AppUtil
/**
     * 关闭该控件的软键盘
     * */
    public static void closeKeyBoard(Context ctx,EditText editText) {
        try {
            InputMethodManager imm = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 隐藏软键盘
     * */
    public static void hideSoftKeyboard(Activity act){
        InputMethodManager manager = (InputMethodManager) act.getSystemService(Activity.INPUT_METHOD_SERVICE);
        View focus = act.getCurrentFocus();
        manager.hideSoftInputFromWindow(
                focus == null ? null : focus.getWindowToken(),
                InputMethodManager.HIDE_NOT_ALWAYS);
    }

    public static void hideSoftKeyboard(IBinder token, Context context){
        InputMethodManager inputMethodManager = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
    }
4、ScrollView的坑!!!

1、一般来说直接传parent_resid就可以了。但是!!!
2、scrollview不能onclick监听,但是要监听他的点击和滑动就得用ontouch监听
3、如果parent下有个差不多占据整个屏幕的scrollview请传scrollview_resid比较好,因为parent_resid被遮挡了,监听不到。。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章