Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
72 views
in Technique[技术] by (71.8m points)

java - TextWatcher not executing several setText llines

Using TextWatcher to change letters, it seems to only execute the last line (For example it would change c to 3 but ignore the changes prior. If I delete the last line (c to 3) it would only then start changing b to 2. Im not sure why this is or how to fix it. (Java is new to me)

public class MainActivity extends AppCompatActivity {

TextWatcher tt = null;

private TextView textView;
private EditText editText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final EditText et = (EditText) findViewById(R.id.editText);
    final TextView tv = (TextView) findViewById(R.id.textView);

    tt = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

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

            et.removeTextChangedListener(tt);
            tv.setText(et.getText().toString().replace("a", "1"));
            tv.setText(et.getText().toString().replace("b", "2"));
            tv.setText(et.getText().toString().replace("c", "3"));
            et.addTextChangedListener(tt);


        }

        @Override
        public void afterTextChanged(Editable s) {

                et.setSelection(s.length());

        }
    };
    et.addTextChangedListener(tt);
question from:https://stackoverflow.com/questions/65925054/textwatcher-not-executing-several-settext-llines

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In the code provided there are 3 times setText executed for TextView. So, it keeps the result only of the last call. If you want to display result of all replacements, do it in single String:

et.removeTextChangedListener(tt);
tv.setText(et.getText().toString().replace("a", "1").replace("b", "2").replace("c", "3"));
et.addTextChangedListener(tt);

EDIT:

Of course, you can execute transformation step-by-step:

et.removeTextChangedListener(tt);
String s = et.getText().toString();
s = s.replace("a", "1");
s = s.replace("b", "2");
s = s.replace("c", "3");
tv.setText(s);
et.addTextChangedListener(tt);

Method String.replace doesn't change String, but returns new one, so we need to reassign results of each replacement (I just assign to s again and again to prevent unused references)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...