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.
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.
Then say for example you need to call it from activity, call it as follows;
Notice
This gives us the root view of the current group(you mustn't have set the id on root view).
Cheers :)
Activity
ScreenUtils
I find the accepted answer a bit complicated.
Here's my solution. Add an
OnTouchListener
to your main layout, ie.:and put the following code in the onTouch method.
This way you don't have to iterate over all views.
To solve this problem what you have to do is first use setOnFocusChangeListener of that Edittext
and then what you need to do is override dispatchTouchEvent in the activity which contains that Edittext see below code
Now what will happen is when a user click outside then firstly this dispatchTouchEvent will get called which then will clear focus from the editext now your OnFocusChangeListener will get called that focus has been changed now here you can do anything which you wanted to do hope it works
I find the accepted answer bit complex for this simple requirement. Here's what worked for me without any glitch.
Plea: I recognize I have no clout, but please take my answer seriously.
Problem: Dismiss soft keyboard when clicking away from keyboard or edit text with minimal code.
Solution: External library known as Butterknife.
One Line Solution:
More Readable Solution:
Explanation: Bind OnClick Listener to the activity's XML Layout parent ID, so that any click on the layout (not on the edit text or keyboard) will run that snippet of code which will hide the keyboard.
Example: If your layout file is R.layout.my_layout and your layout id is R.id.my_layout_id, then your Butterknife bind call should look like:
Butterknife Documentation Link: http://jakewharton.github.io/butterknife/
Plug: Butterknife will revolutionize your android development. Consider it.
Note: The same result can be achieved without the use of external library Butterknife. Just set an OnClickListener to the parent layout as described above.