Ok everyone knows that to hide a keyboard you need to implement:
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
But the big deal here is how to hide the keyboard when the user touches or selects any other place that is not an EditText
or the softKeyboard?
I tried to use the onTouchEvent()
on my parent Activity
but that only works if user touches outside any other view and there is no scrollview.
I tried to implement a touch, click, focus listener without any success.
I even tried to implement my own scrollview to intercept touch events but I can only get the coordinates of the event and not the view clicked.
Is there a standard way to do this?? in iPhone it was really easy.
A more Kotlin & Material Design way using TextInputEditText (this approach is also compatible with EditTextView)...
1.Make the parent view(content view of your activity/fragment) clickable and focusable by adding the following attributes
2.Create an extension for all View (inside a ViewExtension.kt file for example) :
3.Create a BaseTextInputEditText that inherit of TextInputEditText. Implement the method onFocusChanged to hide keyboard when the view is not focused :
4.Just call your brand new custom view in your XML :
That's all. No need to modify your controllers (fragment or activity) to handle this repetitive case.
There is a simpler approach, based on iPhone same issue. Simply override the background's layout on touch event, where the edit text is contained. Just use this code in the activity's OnCreate (login_fondo is the root layout):
I got one more solution to hide the keyboard by:
Here pass
HIDE_IMPLICIT_ONLY
at the position ofshowFlag
and0
at the position ofhiddenFlag
. It will forcefully close the soft keyboard.This may be old but I got this working by implenting a custom class
the best practice here is to create a Helper class and every container Relative / Linear Layouts should implement this.
**** Take note only the main Container should implement this class (For optimization) ****
and implement it like this :
the keyword this is for Activity. so if you are on fragment you use like getActivity();
---thumbs up if it help you... --- cheers Ralph ---
I have done this way:
Hide keyboard code:
Done
I got this working with a slight variant on Fernando Camarago's solution. In my onCreate method I attach a single onTouchListener to the root view but send the view rather than activity as an argument.
In a separate Utils class is...