持续循环中的 TextWatcher()

TextWatcher() in constant loop

每次用户输入一个字母时,它都会存储在 outData 中,然后清除 TextView。为什么这是一个恒定的循环?我以为条件语句会退出,但它一直在循环?

  writeText     = (TextView) rootView.findViewById(R.id.WriteText);

  writeText.addTextChangedListener(watch);

  TextWatcher watch = new TextWatcher() {

    @Override
    public void afterTextChanged(Editable arg0) {

        if (writeText.getText() == "") {
            return;
        }
        else{
            String writeData = writeText.getText().toString();
            byte[] OutData = writeData.getBytes();
            ftDevice.write(OutData, writeData.length());
            writeText.setText("");
        }
    }

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

    }

    @Override
    public void onTextChanged(CharSequence s, int a, int b, int c) {

    }
};

有 2 个问题:

1- 字符串不能与==符号进行比较,有一个equals函数可以做到这一点,在这里您可以简单地检查字符串长度== 0作为return的基本条件。

2- 调用 setText() 将再次触发 TextWatcher 回调,而不是编辑作为参数传递的 Editable 对象,更改将得到反映。

这样做:

if (writeText.getText().length() == 0) {
        return;
    }
    else{
        String writeData = writeText.getText().toString();
        byte[] OutData = writeData.getBytes();
        ftDevice.write(OutData, writeData.length());
        arg0.replace(0, arg0.length(), "");
    }

String comparing use 'equals' method.

String1.equals(String2) instead of ==.

equals method is for comparing the contents and == is for comparing the references and primitives ,not to the contents.