首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >EditText的活动字符数

EditText的活动字符数
EN

Stack Overflow用户
提问于 2010-06-10 19:09:00
回答 13查看 80.4K关注 0票数 112

我想知道在Android中对编辑文本框进行实时字符统计的最好方法是什么。我看着this,但我似乎不明白它的意思。

为了描述这个问题,我有一个EditText,并且我试图将字符限制在150个字符以内。我可以使用输入过滤器来实现这一点,但是我希望在文本框的正下方显示用户输入的字符数(几乎就像现在的堆栈溢出一样)。

如果有人能写一小段示例代码,或者给我指明正确的方向,我将不胜感激。

EN

回答 13

Stack Overflow用户

发布于 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);
票数 162
EN

Stack Overflow用户

发布于 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>
票数 32
EN

Stack Overflow用户

发布于 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");

        }
    });
票数 18
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3013791

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档