Android EditText 的实时字符数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3013791/
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-20 08:18:02  来源:igfitidea点击:

Live character count for EditText

android

提问by Taylor Perkins

I was wondering what the best way to do a live character count of an edit-text box is in Android. I was looking at thisbut I couldn't seem to make any sense of it.

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

To describe the problem, I have an EditText and I'm trying to limit the characters to 150. I can do this with an input filter, however I want to show right below the text box the number of characters a user has entered(Almost like stack overflow is doing right now).

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

If someone could write a small snippet of example code or point me in the right direction I'd appreciate it a lot.

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

回答by Cameron Ketcham

you can use a TextWatcher to see when the text has changed

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

you set the TextWatcher for the edittext with

你为edittext设置TextWatcher

mEditText.addTextChangedListener(mTextEditorWatcher);

回答by Midhun Vijayakumar

You can do character counting from xml itself using TextInputLayoutwrapper for EditText introduced in SupportLibrary v23.1

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

Just wrap your EditText with a TextInputLayout and set CounterEnabled to true and Set a counterMaxLength.

只需用 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>

You'll get a material effect like this

你会得到这样一个重大的影响

You may use counterOverflowTextAppearance, counterTextAppearanceto style the counter.

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

EDIT

编辑

From Android documentation.

来自 Android 文档。

The TextInputEditTextclass is provided to be used as a child of this layout. Using TextInputEditText allows TextInputLayout greater control over the visual aspects of any text input. An example usage is as so:

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>

TextInputLayoutTextInputEditText

TextInputLayout TextInputEditText

回答by Daniel Gomez Rico

You can do it with TextInputLayoutand compat libraries with:

您可以使用TextInputLayout和兼容库来做到这一点:

app:counterEnabled="true"
app:counterMaxLength="420"

and complete:

并完成:

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

回答by Amal Kronz

in xml add this attribute for editText

在 xml 中为 editText 添加此属性

    android:maxLength="80"

in java add this listener

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

        }
    });

回答by Depinder Bharti

Its very Simple Follow the instructions below:

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

====Add them to your Imports===

====将它们添加到您的导入中===

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

=====Define this=====

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

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

回答by Rana Pratap Singh

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

回答by mortezahosseini

Just set these 2 lines in TextInputLayoutin your XML file:

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

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

回答by Sathish

You can add a counter to your TextInputEditText being wrapped in a TextInputLayout. As you can see in the example, counterEnabledenables this feature and counterMaxLenghdefines the number of characters for it.

您可以向包装在 TextInputLayout 中的 TextInputEditText 添加一个计数器。正如您在示例中看到的,counterEnabled启用此功能并counterMaxLengh为其定义字符数。

<com.google.android.material.textfield.TextInputLayout
        android:id="@+id/til_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:counterEnabled="true"
        app:counterMaxLength="50">
    <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/et_title"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
</com.google.android.material.textfield.TextInputLayout>

回答by grantespo

This solution uses Kotlinand shows the number of characters left. Also, if the current number of characters surpasses the limit of 50, the text color will change to red.

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

Kotlin

科特林

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

Also, don't forget to add the TextWatcherto your EditText

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

YOUR_EDIT_TEXT_ID.addTextChangedListener(mTitleTextWatcher)

回答by Alireza Ghanbarinia

Use android:maxLength="140"

使用 android:maxLength="140"

That should work. :)

那应该工作。:)

Hope that helps

希望有帮助