Java 获取 EditText 的字符数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2960981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 14:57:38  来源:igfitidea点击:

Getting character count of EditText

javaandroidandroid-edittext

提问by strange quark

I'm trying to get a character count of an EditText. I've looked into different properties of the EditText and TextView classes, but there doesn't seem to be a function that returns the amount of characters. I have tried to use the TextWatcher, but that is not ideal since sometimes I load a saved message into the EditText from the preferences, and TextWatcher does not count characters not typed right then.

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

Any help would be great!

任何帮助都会很棒!

Cheers!

干杯!

采纳答案by Mark B

Just grab the text in the EditText as a string and check its length:

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

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

回答by hunse

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