How to clear focus and remove keyboard on Android?
Make sure your EditText XML has :
android:id="@+id/myEditText"
android:imeOptions="actionDone"
Then set listener to your EditText (with Kotlin, and from a fragment):
myEditText.setOnEditorActionListener({ v, actionId, event ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
myEditText.clearFocus()
val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view!!.windowToken, 0)
}
false
})
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editTextField.getWindowToken(), 0);
In the layout XML file, specify an imeOption on your EditText:
android:imeOptions="actionGo"
Next, add an action listener to your EditText in the Activity's java file
mYourEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_GO) {
// hide virtual keyboard
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mYourEditText.getWindowToken(), 0);
return true;
}
return false;
}
});
Where mYourEditText is an EditText object