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