The OnFocusChangeListener listens for a change. This means losing the focus is a change, too. Try adding
if (hasFocus)
before your toast.
Question
I am exercising the OnFocusListener
and I have created two EditText fields and I wanted to display Toast message when one of the following Text Fields is clicked:
My implementation:
mUsername = (EditText) findViewById(R.id.usernameEdit);
mPassword = (EditText) findViewById(R.id.passwordEdit);
mUsername.setOnFocusChangeListener(new OnFocusChangeListener(){
@Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "Username is on focus", T
Toast.LENGTH_SHORT).show();
}
});
mPassword.setOnFocusChangeListener(new OnFocusChangeListener(){
@Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "Password is on focus",
Toast.LENGTH_SHORT).show();
}
});
However, when the app is launched automatically the username in onFocus
and it shows the Toast message Username is on focus. and when I click on password it shows the Username message first and then password message. And when I click back the username field it shows first the password message and then the username message. I might have implemented the logic here wrong but I could not find it. can anyone help me please.
thank you.
Solution
The OnFocusChangeListener listens for a change. This means losing the focus is a change, too. Try adding
if (hasFocus)
before your toast.