首页 > 解决方案 > EditText addTextChangedListener 无法正常工作

问题描述

我有两个 EditText 输入,当计算后文本发生变化时,我必须在同一活动中的 textView 上显示结果。addTextChangedListener 不适合我

Activity.java code:
width.addTextChangedListener(new TextWatcher() {
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        public void afterTextChanged(Editable s) {

        }

        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
            if(!s.equals("") ) {
                TextView perimeterdetails = (TextView) findViewById(R.id.perimeterdetails);
                perimeterdetails.setText(s);
            }
        }
    });

XML 代码:

<EditText
    android:id="@+id/width"
    android:layout_width="0dp"
    android:background="@drawable/edittextbackground"
    android:layout_weight="1"
    android:inputType="numberDecimal"
    android:layout_height="wrap_content"/>
<TextView
    android:id="@+id/perimeterdetails"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="TextView" />

标签: androidandroid-studio

解决方案


如下更改您的代码onCreate

TextView perimeterdetails = (TextView) findViewById(R.id.perimeterdetails);

并在 onTextChanged 中比较您的字符串,如下所示

if(!TextUtils.isEmpty(s.toString())) {
                perimeterdetails.setText(s);
            }

推荐阅读