I have an EditText
called myTextview
. I want the soft keyboard to show when I click on the EditText
but then dismiss if I click outside of
I found a better solution:
Override the dispatchTouchEvent
method in your Activity.
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
View v = getCurrentFocus();
if (v != null && (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE) &&
v instanceof EditText &&
!v.getClass().getName().startsWith("android.webkit.")) {
int[] sourceCoordinates = new int[2];
v.getLocationOnScreen(sourceCoordinates);
float x = ev.getRawX() + v.getLeft() - sourceCoordinates[0];
float y = ev.getRawY() + v.getTop() - sourceCoordinates[1];
if (x < v.getLeft() || x > v.getRight() || y < v.getTop() || y > v.getBottom()) {
hideKeyboard(this);
}
}
return super.dispatchTouchEvent(ev);
}
private void hideKeyboard(Activity activity) {
if (activity != null && activity.getWindow() != null) {
activity.getWindow().getDecorView();
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0);
}
}
}
This is applicable even if you are working with webview.
UPDATE 10th July 2020
The above method works perfectly but the EditText is still has the focus and typing cursor is still visible.
To solve the described issue. Do this
Add
findViewById(android.R.id.content).setFocusableInTouchMode(true);
in your onCreate() method
Add findViewById(android.R.id.content).clearFocus();
in the
hideKeyboard()
method
Credit to Eddwhis's comment