EditText的实时字符数

时间:2010-06-10 11:09:00

标签: android

我想知道在Android中进行编辑文本框的实时字符计数的最佳方法是什么。我看着this,但我似乎无法理解它。

为了描述这个问题,我有一个EditText,我试图将字符限制为150.我可以使用输入过滤器执行此操作,但是我想在文本框的正下方显示用户拥有的字符数输入(几乎像堆栈溢出现在正在进行)。

如果有人可以写一小段示例代码或指向正确的方向,我会非常感激。

15 个答案:

答案 0 :(得分:145)

您可以使用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) {
        }
};

使用

为edittext设置TextWatcher
mEditText.addTextChangedListener(mTextEditorWatcher);

答案 1 :(得分:94)

您可以使用memcached中引入的EditText的TextInputLayout包装器从xml本身进行字符计数

使用TextInputLayout包装EditText并将CounterEnabled设置为true并设置counterMaxLength。

<android.support.design.widget.TextInputLayout
    android:id="@+id/textContainer"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:counterEnabled="true"
    app:counterMaxLength="20"
    >
    <EditText
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Text Hint"
        />
</android.support.design.widget.TextInputLayout>

您将获得类似SupportLibrary v23.1

的素材效果

您可以使用 counterOverflowTextAppearance counterTextAppearance 来设置计数器的样式。

修改

来自Android文档。

提供 TextInputEditText 类作为此布局的子级。使用TextInputEditText允许TextInputLayout更好地控制任何文本输入的可视方面。示例用法如下:

     <android.support.design.widget.TextInputLayout
         android:layout_width="match_parent"
         android:layout_height="wrap_content">

     <android.support.design.widget.TextInputEditText
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:hint="@string/form_username"/>

 </android.support.design.widget.TextInputLayout>

this TextInputLayout

答案 2 :(得分:18)

您可以使用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>

答案 3 :(得分:9)

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

        }
    });

答案 4 :(得分:6)

非常简单按照以下说明操作:

====将它们添加到您的Imports ===

import android.text.Editable;
import android.text.TextWatcher;

=====定义这个=====

private TextView sms_count;

========== Inside On Create =====

sms_count = (TextView) findViewById(R.id.textView2);


final TextWatcher txwatcher = new TextWatcher() {
   public void beforeTextChanged(CharSequence s, int start, int count, int after) {
   }

   public void onTextChanged(CharSequence s, int start, int before, int count) {

      sms_count.setText(String.valueOf(s.length()));
   }

   public void afterTextChanged(Editable s) {
   }
};

sms_message.addTextChangedListener(txwatcher);

答案 5 :(得分:5)

    You can use TextWatcher class to see text has changed and how much number of character remains.Here i have set counter of 140 characters.

    EditText typeMessageToPost;
    TextView number_of_character;
public void onCreate(Bundle savedBundleInstance) {
        super.onCreate(savedBundleInstance);
setContentView(R.layout.post_activity);
typeMessageToPost.addTextChangedListener(mTextEditorWatcher);
}
private final TextWatcher mTextEditorWatcher=new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            number_of_character.setText(String.valueOf(140-s.length()));
        }
    };

答案 6 :(得分:4)

只需在XML文件的TextInputLayout中设置这两行:

app:counterEnabled="true"
app:counterMaxLength="200"

答案 7 :(得分:1)

我遇到了同样的问题,我尝试了Cameron的方法。它有效,但有一个小错误:如果用户使用复制和粘贴,则无法计算字符数。因此我建议在文本更改后执行,如下所示:

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

         }

          public void afterTextChanged(Editable s) {
             //This sets a textview to the current length
             mTextView.setText(String.valueOf(s.length()));
         }
    };

答案 8 :(得分:1)

使用android:maxLength =&#34; 140&#34;

那应该有用。 :)

希望有所帮助

答案 9 :(得分:1)

如果您使用androidX库而不是旧版支持库

<input class="_2hvTZ pexuQ zyHYP" id="f3276ee98b5533" aria-label="Phone number, username, or email" aria-required="true" autocapitalize="off" autocorrect="off" maxlength="75" name="username" type="text" value="">
<input class="_2hvTZ pexuQ zyHYP" id="f184fc168fd6684" aria-label="Password" aria-required="true" autocapitalize="off" autocorrect="off" name="password" type="password" value="">

答案 10 :(得分:0)

尝试做这样的事情。

与获取CharSequence.length相比,此解决方案可能更高效。每次点击软键盘,事件都会触发;因此,如果你做一个长度,它将每次计算CharSequence,如果你开始进入大型CharSequnces,这可能会减慢。文本更改的事件监听器将计算前后计数。这适用于递增和递减值

@Override
        public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
            int tick = start + after;
            if(tick < mMessageMax) {
                int remaining = mMessageMax - tick;
                ((TextView)findViewById(R.id.contact_us_chars)).setText(String.valueOf(remaining));
            }
        }

答案 11 :(得分:0)

尝试

private TextWatcher textWatcher = new TextWatcher() {
    @Override
    public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {
        editText.post(new Runnable() {
            @Override
            public void run() {
                if (length < 100) {
                    if (count > 0 && after <= 0)/*remove emoij*/ {
                        length--;
                    } else if (count > after)/*remove text*/ {
                        length--;
                    } else if (count == 0 && after > 1)/*emoij*/ {
                        ++length;
                    } else if (count == 0 && after == 1)/*Text*/ {
                        ++length;
                    } else if (count > 0 && after > 1) {
                        ++length;
                    }
                    if (s.length() <= 0)
                        length = 0;
                    Log.w("MainActivity", " Length: " + length);
                } else {
                    if (count > 0 && after <= 0)/*remove emoij*/ {
                        length--;
                    } else if (count > after)/*remove text*/ {
                        length--;
                    }
                    Log.w("MainActivity", " Length: " + length);
                }

                if (length == 100) {
                    editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(s.length())});
                } else {
                    editText.setFilters(new InputFilter[]{});
                }
            }
        });
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {

    }
};

`

答案 12 :(得分:0)

此解决方案使用Kotlin并显示剩余字符数。另外,如果当前字符数超过了限制50,则文本颜色将变为红色。

科特林

private val mTitleTextWatcher = object : TextWatcher {
    override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}

    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
        if(YOUR_EDIT_TEXT_ID.text.toString().trim().length < 51){
            YOUR_CHAR_LEFT_TEXTVIEW_ID.text = (50 - YOUR_EDIT_TEXT_ID.text.toString().trim().length).toString()
            YOUR_CHAR_LEFT_TEXTVIEW_ID.setTextColor(Color.BLACK)
        }
        else{
            YOUR_CHAR_LEFT_TEXTVIEW_ID.text = "0"
            YOUR_CHAR_LEFT_TEXTVIEW_ID.setTextColor(Color.RED)
        }
    }

    override fun afterTextChanged(s: Editable) {}
}

此外,不要忘记将TextWatcher添加到您的EditText

YOUR_EDIT_TEXT_ID.addTextChangedListener(mTitleTextWatcher)

答案 13 :(得分:0)

清除方法;

abstract class CharacterWatcher : TextWatcher {
    override fun afterTextChanged(text: Editable?) {
        afterCharacterChanged(text?.lastOrNull(), text?.length)
    }

    override fun beforeTextChanged(text: CharSequence?, start: Int, count: Int, before: Int) {}

    override fun onTextChanged(text: CharSequence?, start: Int, before: Int, count: Int) {}

    abstract fun afterCharacterChanged(char: Char?, count: Int?)
}



 editText.addTextChangedListener(new CharacterWatcher() {
            @Override
            public void afterCharacterChanged(@Nullable Character character, @Nullable Integer count) {
                action()
            }
        });

答案 14 :(得分:0)

     edtmm.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) {
                    int data = Integer.parseInt(String.valueOf(s.length()));
                    if (data == 2) {
                        edtdd.requestFocus();
                    } else {
                        edtmm.requestFocus();
                    }
                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });