使用setText()不想调用textwatcher事件? [重复]

问题描述 投票:3回答:1

我正在使用EditText。当我使用setText()时。 TextWatcher事件正在调用。我不需要打电话吗?谁能帮我吗?

        txt_qty.addTextChangedListener(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) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

谢谢。

android android-edittext settext android-textwatcher
1个回答
6
投票

您可以注销观察者,然后重新注册。

要注销监视者,请使用此代码:

txt_qty.removeTextChangedListener(yourTextWatcher);

使用此代码重新注册它:

txt_qty.addTextChangedListener(yourTextWatcher);

或者,您可以设置一个标志,以便观察者知道您何时刚刚更改了文本(因此应该忽略它)。>>

在您的活动中定义一个标志是:boolean isSetInitialText = false;

并且当您调用txt_qty.settext(yourText)时,请在调用设置文本之前先使isSetInitialText = true,>

然后将您的观察者更新为:

txt_qty.addTextChangedListener(new TextWatcher() {
            @Override 
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
          if (isSetInitialText){
                isSetInitialText = false;
          } else{
                  // perform your operation
          }

            @Override 
            public void onTextChanged(CharSequence s, int start, int before, int count) {
              if (isSetInitialText){
                   isSetInitialText = false;
               } else{
                 // perform your operation
               }
            } 

            @Override 
            public void afterTextChanged(Editable s) {
                 if (isSetInitialText){
                      isSetInitialText = false;
                 } else{
                     // perform your operation
                 }
            } 
        }); 
© www.soinside.com 2019 - 2024. All rights reserved.