zoukankan      html  css  js  c++  java
  • Android中点击隐藏软键盘最佳方法——Android开发之路4

     Android中点击隐藏软键盘最佳方法

     实现功能:点击EditText,软键盘出现并且不会隐藏,点击或者触摸EditText以外的其他任何区域,软键盘被隐藏;

    1、重写dispatchTouchEvent()方法,获取当前触摸事件为DOWN的时候隐藏软键盘

    @Override
        public boolean dispatchTouchEvent(MotionEvent ev) {
            //Finger touch screen event
            if (ev.getAction() == MotionEvent.ACTION_DOWN) {
                // get current focus,Generally it is EditText
                View view = getCurrentFocus();
                if (isShouldHideSoftKeyBoard(view, ev)) {
                    hideSoftKeyBoard(view.getWindowToken());
                }
            }
            return super.dispatchTouchEvent(ev);
        }

    2、isShouldHideInput()方法;

    /**
         * Judge what situation hide the soft keyboard,click EditText view should show soft keyboard
         * @param v Incident event
         * @param event 
         * @return
         */
        private boolean isShouldHideSoftKeyBoard(View view, MotionEvent event) {
            if (view != null && (view instanceof EditText)) {
                int[] l = { 0, 0 };
                view.getLocationInWindow(l);
                int left = l[0], top = l[1], bottom = top +view.getHeight(), right = left
                        + view.getWidth();
                if (event.getX() > left && event.getX() < right
                        && event.getY() > top && event.getY() < bottom) {
                    // If click the EditText event ,ignore it
                    return false;
                } else {
                    return true;
                }
            }
            // if the focus is EditText,ignore it; 
            return false;
        }

    3、hideSoftKeyBoard()方法;

    /**
         * hide soft keyboard
         * @param token
         */
        private void hideSoftKeyBoard(IBinder token) {
            if (token != null) {
                InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                im.hideSoftInputFromWindow(token,
                        InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
  • 相关阅读:
    UVA-1623 Enter The Dragon (贪心)
    UVA-1619 Feel Good (单调队列)
    UVA-11536 Smallest Sub-Array
    UVA-1617 Laptop (贪心)
    UVA-10570 Meeting with Aliens (枚举+贪心)
    UVA-1153 Keep the Customer Satisfied (贪心)
    UVA-1614 Hell on the Markets(贪心+推理) (有待补充)
    UVA-1613 K-Graph Oddity (着色问题)
    UVA-1612 Guess (贪心)
    todo:open和fopen的区别
  • 原文地址:https://www.cnblogs.com/shen-hua/p/6029902.html
Copyright © 2011-2022 走看看