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.
Focusable in touch mode is a property that you can set yourself either from code or XML. However, it should be used sparingly and only in very specific situations as it breaks consistency with Android normal behavior.
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) { }
}
Using Java 8 lambda expression:
editText.setOnFocusChangeListener((v, hasFocus) -> {
if(!hasFocus) {
String value = String.valueOf( editText.getText() );
}
});
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