【问题标题】:Dynamic Word Count for EditTextEditText 的动态字数
【发布时间】:2017-05-18 18:16:39
【问题描述】:

我正在尝试获取编辑文本的动态或实时字数。 为了解释这个问题,我在片段中有一个 EditText 和一个 Textview,每当用户在 EditText 中输入一个句子时,它应该自动计算该句子中出现的单词数并在 TextView 中显示单词数。

我已经实现了文本观察器,但无法弄清楚代码 sn-p。

任何帮助将不胜感激。

【问题讨论】:

标签: android android-studio android-edittext android-textwatcher


【解决方案1】:

TextWatcher 的回调之一是afterTextChanged(Editable edit)

Editable 是当您在 EditText 上调用 getText 时得到的,它保存当前文本,因此也知道当前文本的长度。

所以你可以这样做:

        editText.addTextChangedListener(new TextWatcher() {
            ...
            @Override
            public void afterTextChanged(Editable editable) {
                String currentText = editable.toString();
                int currentLength = currentText.length();
                textView.setText("Current length: " + currentLength);
            }
        });

【讨论】:

  • 这段代码返回字符数,我需要在editText中输入的字数。
  • 然后用空格分割 currentText 并在返回的数组上使用 .length 。这就是整个文本中有多少个单词。
  • 当你用回车分隔单个单词时它不起作用。
猜你喜欢
  • 2020-09-14
  • 2014-01-26
  • 1970-01-01
  • 2015-09-05
  • 2012-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-20
相关资源
最近更新 更多