Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change TextView text on DataChange without calling back a TextWatcher listener

Consider:

TextView textView = new TextView(context);
    textView.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {

            s.append("A");
        }
    });

If we add a TextWatcher to a TextView, and I want to append a letter to this TextView, every time the user writes a letter in it, but this keeps calling the TextWatcher Listener, so on to StackOverFlow error, so how can I append text without calling the TextWatcher Listener again?

like image 552
Mohammad Ersan Avatar asked Jun 15 '11 08:06

Mohammad Ersan


People also ask

How can I change the EditText text without triggering the text watcher?

public class MyTextWatcher implements TextWatcher { private EditText editText; // Pass the EditText instance to TextWatcher by constructor public MyTextWatcher(EditText editText) { this. editText = editText; } @Override public void afterTextChanged(Editable e) { // Unregister self before update editText.

What is editable in Android?

This is the interface for text whose content and markup can be changed (as opposed to immutable text like Strings). If you make a DynamicLayout of an Editable, the layout will be reflowed as the text is changed.

What is the use of TextWatcher in Android?

EditText is used for entering and modifying text. While using EditText width, we must specify its input type in inputType property of EditText which configures the keyboard according to input. EditText uses TextWatcher interface to watch change made over EditText.


1 Answers

Another way to avoid a stack overflow:

TextView textView = new TextView(context);
    textView.addTextChangedListener(new TextWatcher() {

        boolean editing = false;

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!editing){
               editing = true;
               s.append("A");
               editing = false;
        }

    }
});
like image 83
Iurii Vasylenko Avatar answered Oct 02 '22 13:10

Iurii Vasylenko