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:

  • Username
  • Password

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.

Was it helpful?

Solution

The OnFocusChangeListener listens for a change. This means losing the focus is a change, too. Try adding

if (hasFocus)

before your toast.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top