I need to hide the softkeypad in android when user click on anywhere other than a Edittext. There are many help for iphone but not for android. I tried this code but its not working :(
final RelativeLayout base = (RelativeLayout) findViewById(R.id.RelativeLayout1);
findViewById(R.id.base).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(base.getWindowToken(), 0);
}
});
Thanks in advance !
I tried this to hide Keyboard. You need to pass the method in your Layout file.
The best work around I found was using as below,
Override
dispatchTouchEvent()
and try to get the area ofEditText
usingRect
Method that caculates 4 corner of View(here its EditText)
By using above code we can detect the area of
EditText
and we can check if the touch on the screen is part of the area ofEditText
or not. If its part ofEditText
then don't do anything let the touch do its job, and if the touch doesn't contain area ofEditText
then just close the softkeyboard.******EDIT******
I just found another approach if we don't want to give any EditText as input and want to hide keyboard inside whole application when user touches anywhere else other than EditText. Then you have to create an BaseActivity and write global code for hiding keyboard as below,
For those who are looking for a Xamarin code for this, here you go :
Well I have done this way:
Add code in your Activity.
This would work for Fragment also, no need to add this code in Fragment.
Hope this will help you.
Call this method in your
MainAcitivity.class
You can use the
onTouchEvent()
to hide theSoftkeyboard
.Though this solution works, but the best I would suggest is to use below answer as it gives best solution of closing the keyboard touching anywhere else then EditText.