I have two EditText
fields in my activity and a done button
. I want both the EditText
fields to loose focus (that is the cursor should not not be displayed on either of them) when the user presses the button. I am using the following code:
final Button saveButton = (Button) findViewById(R.id.saveButton); saveButton.setOnClickListener(saveButtonListener); private OnClickListener saveButtonListener = new OnClickListener() { @Override public void onClick(View v) { Text1.clearFocus(); Text2.clearFocus(); } }
However, when I press the done button, the cursor comes up on Text1
even if I haven't clicked on any EditText
yet. How can I make the EditText fields loose focus on the click of the button
setOnClickListener(saveButtonListener); private OnClickListener saveButtonListener = new OnClickListener() { @Override public void onClick(View v) { Text1. clearFocus(); Text2. clearFocus(); findViewById(R. id.
You can use View. OnFocusChangeListener to detect if any view (edittext) gained or lost focus. This goes in your activity or fragment or wherever you have the EditTexts.
try by Changing your code as:
private OnClickListener saveButtonListener = new OnClickListener() { @Override public void onClick(View v) { Text1.clearFocus(); Text2.clearFocus(); saveButton.requestFocus(); //or any other View } }
because as doc as about public void clearFocus () :
Called when this view wants to give up focus. If focus is cleared onFocusChanged(boolean, int, android.graphics.Rect) is called.
Note: When a View clears focus the framework is trying to give focus to the first focusable View from the top. Hence, if this View is the first from the top that can take focus, then all callbacks related to clearing focus will be invoked after wich the framework will give focus to this view.
means you must set Focus to other view on button click because Text1
act as first View in your layout
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With