Skip to content

Instantly share code, notes, and snippets.

@elqsar
Last active September 12, 2022 11:06
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save elqsar/9278206 to your computer and use it in GitHub Desktop.
Save elqsar/9278206 to your computer and use it in GitHub Desktop.
Hide softkeyboard in android application if user tap outside EditText control
protected void setupParent(View view) {
//Set up touch listener for non-text box views to hide keyboard.
if(!(view instanceof EditText)) {
view.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
hideSoftKeyboard();
return false;
}
});
}
//If a layout container, iterate over children
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
View innerView = ((ViewGroup) view).getChildAt(i);
setupParent(innerView);
}
}
}
private void hideSoftKeyboard() {
InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
}
@greatvova
Copy link

greatvova commented Aug 14, 2018

Same code in C# for Xamarin:

protected void SetupParent(View view)
        {
            //Set up touch listener for non-text box views to hide keyboard.
            if (view.GetType() != typeof(EditText))
            {
                view.Touch += (sender, e) => 
                {
                    var inputManager = (InputMethodManager)GetSystemService(InputMethodService);
                    inputManager.HideSoftInputFromWindow(messagesRecyclerView.WindowToken, HideSoftInputFlags.None);
                };
            }

            //If a layout container, iterate over children
            if (view.GetType() != typeof(ViewGroup))
            {
                var v = (ViewGroup)view;
                for (int i = 0; i < v.ChildCount; i++)
                {
                    View innerView = ((ViewGroup)view).GetChildAt(i);
                    SetupParent(innerView);
                }
            }
        }

@dphans
Copy link

dphans commented Sep 12, 2022

Your code is right way, but may be override onClick on other Views. Eg. Button onClick,...
In this case, you can add flag to view which need to handle tap to close keyboard is better.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment