0

I want to hide the Soft Keyboard by touching the background or the linearlayout. How can I do it?

Can anyone Help Me? Please

Kiel
  • 41
  • 7
  • visit this http://stackoverflow.com/questions/4165414/how-to-hide-soft-keyboard-on-android-after-clicking-outside-edittext – H Raval Dec 23 '15 at 10:22
  • 2
    Possible duplicate of [hide keyboard when user taps anywhere else on the screen in android](http://stackoverflow.com/questions/8697499/hide-keyboard-when-user-taps-anywhere-else-on-the-screen-in-android) – Aditya Vyas-Lakhan Dec 23 '15 at 10:29
  • see my answer http://stackoverflow.com/questions/4165414/how-to-hide-soft-keyboard-on-android-after-clicking-outside-edittext/36786783#36786783 – Uzair Apr 22 '16 at 06:51

3 Answers3

1

You can hide soft keyboard on onClick event of your root view

linearLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
                }
                }
            });
Bhargav Thanki
  • 4,924
  • 2
  • 37
  • 43
1

try to use onTouchEvent

@Override
    public boolean onTouchEvent(MotionEvent event) {
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.
                                                        INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        return true;
    }
Aditya Vyas-Lakhan
  • 13,409
  • 16
  • 61
  • 96
1

As per suggested by the H Raval , this is the best solution. function setupUI in the answer will iterate through your ViewGroup and add onTouch listener to every other view except EditText which is right way to call the code which hides the keyboard.

Code :-

public void setupUI(View view) {

    //Set up touch listener for non-text box views to hide keyboard. 
    if(!(view instanceof EditText)) {

        view.setOnTouchListener(new OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {
                hideSoftKeyboard(MyActivity.this); 
                return false; 
            } 

        }); 
    } 

    //If a layout container, iterate over children and seed recursion. 
    if (view instanceof ViewGroup) {

        for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {

            View innerView = ((ViewGroup) view).getChildAt(i);

            setupUI(innerView);
        } 
    } 
} 

public static void hideSoftKeyboard(Activity activity) {
    InputMethodManager inputMethodManager = (InputMethodManager)  activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
} 
Community
  • 1
  • 1
Nakul
  • 1,313
  • 19
  • 26