Last active
September 12, 2022 11:06
-
-
Save elqsar/9278206 to your computer and use it in GitHub Desktop.
Hide softkeyboard in android application if user tap outside EditText control
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
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
Same code in C# for Xamarin: