How can I know when an EditText loses focus?
Implement onFocusChange
of setOnFocusChangeListener
and there's a boolean parameter for hasFocus. When this is false, you've lost focus to another control.
EditText txtEdit = (EditText) findViewById(R.id.edittxt);
txtEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
// code to execute when EditText loses focus
}
}
});
Have your Activity
implement OnFocusChangeListener()
if you want a factorized use of this interface,
example:
public class Shops extends AppCompatActivity implements View.OnFocusChangeListener{
In your OnCreate
you can add a listener for example:
editTextResearch.setOnFocusChangeListener(this);
editTextMyWords.setOnFocusChangeListener(this);
editTextPhone.setOnFocusChangeListener(this);
then android studio will prompt you to add the method from the interface, accept it... it will be like:
@Override
public void onFocusChange(View v, boolean hasFocus) {
// todo your code here...
}
and as you've got a factorized code, you'll just have to do that:
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus){
doSomethingWith(editTextResearch.getText(),
editTextMyWords.getText(),
editTextPhone.getText());
}
}
That should do the trick!
Kotlin way
editText.setOnFocusChangeListener { _, hasFocus ->
if (!hasFocus) { }
}