Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make EditText lose focus on clicking a button

Tags:

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

like image 456
Ankush Avatar asked Nov 30 '12 11:11

Ankush


People also ask

How do you make EditText lose focus?

setOnClickListener(saveButtonListener); private OnClickListener saveButtonListener = new OnClickListener() { @Override public void onClick(View v) { Text1. clearFocus(); Text2. clearFocus(); findViewById(R. id.

How do I know if EditText has focus?

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.


1 Answers

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

like image 72
ρяσѕρєя K Avatar answered Oct 19 '22 19:10

ρяσѕρєя K