首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >EditText addTextChangedListener不能正常工作

EditText addTextChangedListener不能正常工作
EN

Stack Overflow用户
提问于 2018-12-01 14:42:07
回答 6查看 1.6K关注 0票数 1

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

代码语言:javascript
复制
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代码:

代码语言:javascript
复制
<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" />
EN

回答 6

Stack Overflow用户

发布于 2018-12-01 14:57:53

按如下所示更改代码在onCreate中定义此代码

代码语言:javascript
复制
TextView perimeterdetails = (TextView) findViewById(R.id.perimeterdetails);

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

代码语言:javascript
复制
if(!TextUtils.isEmpty(s.toString())) {
                perimeterdetails.setText(s);
            }
票数 1
EN

Stack Overflow用户

发布于 2018-12-01 14:47:44

因为您是在onTextChanged中定义文本视图

剪切此行TextView perimeterdetails = (TextView) findViewById(R.id.perimeterdetails);

在addTextChangedListener之前

票数 0
EN

Stack Overflow用户

发布于 2018-12-01 14:54:54

尝尝这个

代码语言:javascript
复制
  TextView perimeterdetails = (TextView) findViewById(R.id.perimeterdetails);

    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("") ) {

                perimeterdetails.setText(s);
            }
        }
    });
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53568438

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档