edittext addtextchange 侦听器重复文本

edittext addtextchange listener reapeting text

我见过很多例子,但没有一个适合我。我想要的是通过 EditText 的 addTextChangeListener() 将文本设置到 TextView。但是我在 edittext 中输入的每个字符都会重复我的 textview 文本。

这是我的代码:

edtFromName.addTextChangedListener(new TextWatcher() {
            private String lastValue = "";
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            @Override
            public void afterTextChanged(Editable s) {
                setMessage();
            }
        });

// setMessage code:
  private void setMessage() {

        if (refVia.getSelectedItemPosition() < 3) {
            if (txtCompany.equals("")) {
                txtText.append(" or ");
            } else {
                txtText.append(" " + txtCompany + " or ");
            }
        } else {
            if (txtSupplier.equals("")) {
                txtText.append(" or ");
            } else {
                txtText.append(" " + txtSupplier + " or ");
            }
        }

        txtText.append(edtFromName.getText().toString() + ".");
    }

输出:

Edittext:  sagar

textview: s
textview: sa
textview: sag
textview: saga
textview: sagar

好的,所以要追加。

int mainStringLength = txtText.getText().toString().length();
int nameStringLength = edtFromName.getText().toString().length();
String trimString = txtText.getText().toString().substring(0,(mainStringLength - nameStringLength); 

//Now set this string.
txtText.setText(trimString);