addTextChangedListener仅用于用户输入

addTextChangedListener仅用于用户输入

本文介绍了EditText addTextChangedListener仅用于用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个EditText,可在其中侦听文本更改:

I have an EditText where I listen for changes in text:

editText.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) {
            // do stuff
        }
    });

到目前为止,这仍然可以正常工作,如果我在EditText中键入内容,则执行afterTextChanged()中的内容。现在,在同一活动中,我有一个ToggleButton,它可以更改EditText中的字符串。我如何防止由于ToggleButton触发 afterTextChanged而导致文本更改?

This works fine so far, if I type something in the EditText, things in afterTextChanged() are executed. Now, in the same activity I have a ToggleButton which can change the string in the EditText. How do I prevent this text change due to the ToggleButton to trigger "afterTextChanged"?

PS:不确定是否与此相关,但是特别是我有一个EditText接受小数或小数(例如 0.75或 3/4),并且切换按钮应在小数和小数显示之间切换,但不应触发 afterTextChanged中的任何内容,因为该值保持不变(3/4 = 0.75)。

PS: Not sure whether this is relevant, but specifically I have an EditText which accepts decimal or fractional numbers (e.g. "0.75" or "3/4") and the toggle button should toggle between fractional and decimal display, but should not trigger anything in "afterTextChanged" since the value stays the same (3/4=0.75).

推荐答案

我认为有两种可能性:


  1. 注册/取消注册侦听器

  2. 标志

标志示例:

public class MainActivity extends AppCompatActivity{
    boolean automaticChanged = false;
    ToggleButton toggleButton;
    EditText editText;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            //...
            toggleButton.setOnClickListener(onClickListener);
            editText.addTextChangedListener(textWatcher);
            //...
        }

        TextWatcher textWatcher = 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) {
                if (!automaticChanged) {
                    // do stuff
                } else {
                    automaticChanged = false;
                }
            }
        };

        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                automaticChanged = true;
                // do stuff
            }
        };
    }
}

这篇关于EditText addTextChangedListener仅用于用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 19:44