Force Edittext To Lose Focus When: Some Keyboard Keys Are Pressed And When User Clicks On Something Else In The Activity
I know this question has been asked in many different ways before, but even though I have looked at many other related questions about EditText focus, I have not found my solution.
Solution 1:
To make editText lose focus when you press outside of the keyboard you can try to setOnTouchListener to the view that is visible when the keyboard is shown. For example, it might be the parent layout, listView, recyclerView or any other significant in size view. In order to do that, just add code below inside of your onCreate
method in activity:
findViewById(R.id.loginLayout).setOnTouchListener(newView.OnTouchListener() {
@OverridepublicbooleanonTouch(View v, MotionEvent event) {
InputMethodManagerimm= (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
usernameEditText.clearFocus();
passwordEditText.clearFocus();
returnfalse;
}
});
To make editText lose focus and/or hide keyboard when pressing some button on keyboard you can use the following code. There is an example of listener for Enter
key. You may find all the other keys on official documentation.
yourEditText.setOnKeyListener(newView.OnKeyListener() {
@OverridepublicbooleanonKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER) {
if (event.getAction() == KeyEvent.ACTION_UP) {
yourEditText.clearFocus();
InputMethodManagerimm= (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}
returnfalse;
}
});
Solution 2:
This Solution works For SOFTKEYS, some code is from here
The final solution to hide keyboard and clear focus from the EditText
would be;
yourEditText.setOnEditorActionListener(newTextView.OnEditorActionListener() {
@OverridepublicbooleanonEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
name.clearFocus();
InputMethodManagerimm= (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
Log.d(TAG, "actionID: " + actionId +" KeyEvent: " + event);
}
returnfalse;
}
});
Post a Comment for "Force Edittext To Lose Focus When: Some Keyboard Keys Are Pressed And When User Clicks On Something Else In The Activity"