Jim
Jim

Reputation: 1986

Proper method to change EditText contents in OnTextChanged event

This code below causes infinate loop problem (as documented). So how do I set the editText contents? I have a text message app where the EditText says "Type to compose",I want to remove the instructions once a user starts to enter a message. TIA

et.addTextChangedListener(new TextWatcher() {
            public void afterTextChanged(Editable s) {
            }
           public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        if(et.getText().toString().equals(getString(R.string.txtMessage_type_to_compose))) {
        try {
            et.setText("");
        } catch (Exception e) {
             Log.d(TAG,"exception : " + e.toString());
        }   
            }
  });

Upvotes: 1

Views: 1263

Answers (1)

Cristian
Cristian

Reputation: 200080

You are doing the wrong way. Instead, use this in your EditText:

<EditText
    ....
    android:hint="Type to compose"/>

The OS will take care of removing that text, and you won't have to workaround that. Also, it will look prettier.

Upvotes: 2

Related Questions