How to hide soft keyboard on android after clicking outside EditText?

前端 未结 30 1770
醉话见心
醉话见心 2020-11-22 11:46

Ok everyone knows that to hide a keyboard you need to implement:

InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hi         


        
30条回答
  •  忘了有多久
    2020-11-22 12:31

    I have refined the method, put the following code in some UI utility class(preferably, not necessarily) so that it can be accessed from all your Activity or Fragment classes to serve its purpose.

    public static void serachAndHideSoftKeybordFromView(View view, final Activity act) {
        if(!(view instanceof EditText)) {
            view.setOnTouchListener(new View.OnTouchListener() {
                public boolean onTouch(View v, MotionEvent event) {
                    hideSoftKeyboard(act);
                    return false;
                }
            });
        }
        if (view instanceof ViewGroup) {
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                View nextViewInHierarchy = ((ViewGroup) view).getChildAt(i);
                serachAndHideSoftKeybordFromView(nextViewInHierarchy, act);
            }
        }
    }
    public static void hideSoftKeyboard (Activity activity) {
        InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
    }
    

    Then say for example you need to call it from activity, call it as follows;

    UIutils.serachAndHideSoftKeybordFromView(findViewById(android.R.id.content), YourActivityName.this);
    

    Notice

    findViewById(android.R.id.content)

    This gives us the root view of the current group(you mustn't have set the id on root view).

    Cheers :)

提交回复
热议问题