我想知道在Android中对编辑文本框进行实时字符统计的最好方法是什么。我看着this,但我似乎不明白它的意思。
为了描述这个问题,我有一个EditText,并且我试图将字符限制在150个字符以内。我可以使用输入过滤器来实现这一点,但是我希望在文本框的正下方显示用户输入的字符数(几乎就像现在的堆栈溢出一样)。
如果有人能写一小段示例代码,或者给我指明正确的方向,我将不胜感激。
发布于 2010-12-16 06:36:01
您可以使用TextWatcher查看文本何时发生更改
private TextView mTextView;
private EditText mEditText;
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
mTextView.setText(String.valueOf(s.length()));
}
public void afterTextChanged(Editable s) {
}
};
设置编辑文本的TextWatcher
mEditText.addTextChangedListener(mTextEditorWatcher);
发布于 2017-08-19 06:40:24
您可以使用TextInputLayout
和compat库来实现这一点,方法如下:
app:counterEnabled="true"
app:counterMaxLength="420"
和完整的:
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:counterEnabled="true"
app:counterMaxLength="420">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLength="420" />
</android.support.design.widget.TextInputLayout>
发布于 2017-05-22 19:03:34
在xml中为editText添加此属性
android:maxLength="80"
在java中添加此监听器
ed_caption.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) {
tv_counter.setText(80 - s.toString().length() + "/80");
}
});
https://stackoverflow.com/questions/3013791
复制相似问题