2

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?

3
  • Clearly, the string you're comparing to is neither "Email" nor "". Print it to Log and check what it actually is. Commented Dec 19, 2011 at 20:58
  • et1.getText() is obviously not returning "Email". The compiler is not broken, break out your debugger and see exactly what it is returning. EDIT: Ninja'd by an evil bag of candy... Commented Dec 19, 2011 at 20:59
  • See best solution here stackoverflow.com/questions/6567527/… Commented Jul 14, 2014 at 9:25

3 Answers 3

9

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

Sign up to request clarification or add additional context in comments.

2 Comments

It worked! Thanks! But strange, I always thought getText() does return a string. :)
It doesn't, it returns an EditText or something similar. I really dislike Java (I know, that's an Android issue, but had Java had operator overloading, all this wouldn't have mattered one bit)
1

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

1 Comment

Why the downvote? Printing out variables is exactly the first step in debugging.
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.