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.
In android, we can set the text of EditText control either while declaring it in Layout file or by using setText() method in Activity file.
Here is the focus listener example.
editText.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if (hasFocus) {
Toast.makeText(getApplicationContext(), "Got the focus", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Lost the focus", Toast.LENGTH_LONG).show();
}
}
});
When in Kotlin it will look like this:
editText.setOnFocusChangeListener { _, hasFocus ->
if (hasFocus) {
toast("focused")
} else {
toast("focuse lose")
}
}
Declare object of EditText on top of class:
EditText myEditText;
Find EditText in onCreate Function and setOnFocusChangeListener of EditText:
myEditText = findViewById(R.id.yourEditTextNameInxml);
myEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if (!hasFocus) {
Toast.makeText(this, "Focus Lose", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Get Focus", Toast.LENGTH_SHORT).show();
}
}
});
It works fine.
For those of us who this above valid solution didnt work, there's another workaround here
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean isFocused) {
if(!isFocused)
{
Toast.makeText(MainActivity.this,"not focused",Toast.LENGTH_SHORT).show();
}
}
});
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