【问题标题】:Getting character count of EditText获取 EditText 的字符数
【发布时间】:2011-02-27 00:10:11
【问题描述】:

我正在尝试获取 EditText 的字符数。我研究了 EditText 和 TextView 类的不同属性,但似乎没有返回字符数量的函数。我曾尝试使用 TextWatcher,但这并不理想,因为有时我会从首选项中将保存的消息加载到 EditText 中,而 TextWatcher 不会计算当时未键入的字符。

任何帮助都会很棒!

干杯!

【问题讨论】:

  • 我知道它已经被回答了。但它可能对其他人有所帮助。您也可以使用 editText.length()

标签: java android android-edittext


【解决方案1】:

只需将 EditText 中的文本作为字符串抓取并检查其长度:

int length = editText.getText().length();

【讨论】:

  • 很好,但是我们如何才能在编辑文本的正下方显示计数 TextView 并且在用户键入时应该可见。我们知道在键盘和编辑文本之间没有空间可以显示任何内容。谢谢。
【解决方案2】:
EditText edittext;
private final TextWatcher mTextEditorWatcher = new TextWatcher() {

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
           //This sets a textview to the current length
           textview.setText(String.valueOf(s.length());
        }

        public void afterTextChanged(Editable s) {
        }
};
 editText.addTextChangedListener(mTextEditorWatcher);

【讨论】:

  • 您可以只获取 EditText 并将其文本作为 String 并获取该字符串的长度。
【解决方案3】:

在 Kotlin 中这很容易

.Text.length

【讨论】:

  • 10 年前被问到 Kotlin 不存在时。
  • 我只想为未来做出贡献。可能对其他人有帮助:)
猜你喜欢
  • 2012-05-17
  • 2012-11-15
  • 2018-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-31
  • 2013-01-12
相关资源
最近更新 更多