Roger Travis
Roger Travis

Reputation: 8538

Comparing text in EditText

My code:

final EditText et1 = (EditText)findViewById(R.id.et1);

        
        et1.setOnFocusChangeListener(new OnFocusChangeListener(){
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if ( hasFocus )
                {
                    et1.setTextColor(0xFF000000);
                    if ( et1.getText().equals("Email") ) { et1.setText(""); }
                }
                else
                { 
                    et1.setTextColor(0xFF7F7F7F);
                    if ( et1.getText().equals("") ) { et1.setText("Email"); }
                }
            }           
        });

et1 has "Email" in it by default. When the user clicks on it, I want it to clear. The OnFocusChangeListener works fine as the color changes, but the text does not change, i.e. the

if ( et1.getText().equals("Email") )

doesn't fire. Nor does the equals(""), after I clear the et.

What am I doing wrong?

Upvotes: 2

Views: 8351

Answers (3)

Joe
Joe

Reputation: 2659

Would android:hint work for you? It basically is doing exactly what you are trying to do, but it is built in.

Upvotes: 1

dotancohen
dotancohen

Reputation: 31471

Print out et1.getText() to see what it contains. It might not be what you think it is.

Upvotes: 1

zmbq
zmbq

Reputation: 39013

Try comparing et1.getText().toString().equals("Email") instead.

Upvotes: 9

Related Questions