如何知道 Android 的 EditText 中发生了删除操作?

Phi*_*lly 5 android textwatcher android-edittext

当一个字符在 EditText 中被删除时,我想得到一个回调。

我该怎么做?

ike*_*fah 5

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

        }
    });
Run Code Online (Sandbox Code Playgroud)

new 在 beforeTextChanged 回调中你有三个参数

  • start 是即将删除的起始索引
  • count 是要删除的文本的长度
  • after 是要添加的文本的长度

现在您只需比较这些参数即可通过回调 beforeTextChanged 实现您想要的任何效果


Ali*_*eli 5

没有直接删除字符的回调!!

但是每次添加任何文本或编辑 EditText 文本时,所有的TextWatcher CallBacks 都会分别调用

(1- beforeTextChanged , 2- onTextChanged , 3- afterTextChanged )

因此,您可以在所有这些中检查删除操作,如下所示。请注意,您不需要在所有回调中检查删除操作。有 3 种方法可以在3 个 TextWatcher CallBacks 中了解 TextWatcher 中的删除操作,每种方法都可以解决您的问题:)

.我认为您最好了解一些 TextWatcher 回调参数。

正如@ikerfah所说

  • start是即将被删除的起始索引
  • count是即将被删除的文本的长度
  • after是即将添加的文本长度

方法 :

  1. beforeTextChanged:您after 参数与 count 参数进行比较
  2. onTextChanged:您在活动或片段中声明一个字段,并在每次onTextChanged调用时填充该字段。将之前 EditText 计数的字段与当前 EditTextCount 的计数参数进行比较;
  3. afterTextChanged:它很像onTextChanged 监听器,只是你使用长度而不是计数。

在下面更改您的最终addTextChangedListener链接:

    yourEditText.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {

        if (after < count) {
            // delete character action have done
            // do what ever you want
            Log.d("MainActivityTag", "Character deleted");
           }
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int start, int before, int count) {

      //mPreviousCount count is fied
         if (mPreviousCount > count) {
                // delete character action have done
                // do what ever you want
                Log.d("MainActivityTag", "Character deleted");
            }
            mPreviousCount=count;
        }

    @Override
    public void afterTextChanged(Editable editable) {
        Log.d("MainActivityTag",editable.toString());
        int length=editable.length();

      //mPreviousLength is a field
        if (mPreviousLength>length)
        {
            // delete character action have done
            // do what ever you want
            Log.d("MainActivityTag", "Character deleted");
        }
        mPreviousLength=length;
    }
 });
Run Code Online (Sandbox Code Playgroud)