edittext addtextchange listener reapeting text

时间:2016-09-17 07:04:34

标签: android android-textwatcher addtextchangedlistener

我见过这么多例子,但没有人为我工作。我想要的是通过EditText的addTextChangeListener()将文本设置为TextView。但是我在texttext中输入的每个字符都重复了我的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

1 个答案:

答案 0 :(得分:0)

好的,可以追加。

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);