Live character count for EditText

后端 未结 14 2071
清歌不尽
清歌不尽 2020-11-29 17:07

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 this but I couldn\'t seem to make any sense of it.

<
相关标签:
14条回答
  • 2020-11-29 18:00

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

    <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>
    
    0 讨论(0)
  • 2020-11-29 18:00

    Try doing something like this.

    This solution may be more performant as opposed to getting CharSequence.length. Each time you tap on the soft keyboard the event fires; therefore, if you do a length it will count the CharSequence each time, which may slow if you start getting into large CharSequnces. The event listener on text change tacks the before and after count. This works well for increment and decrement values

    @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));
                }
            }
    
    0 讨论(0)
提交回复
热议问题