Bạn có thể thực hiện đếm ký tự từ chính xml bằng cách sử dụng trình bao bọc TextInputLayout cho EditText được giới thiệu trong SupportLibrary v23.1
Chỉ cần bọc EditText của bạn bằng một TextInputLayout và đặt CounterEnabled thành true và Đặt 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>
Bạn sẽ nhận được hiệu ứng vật chất như thế này
Bạn có thể sử dụng counterOverflowTextAppearance , counterTextAppearance để tạo kiểu cho bộ đếm.
BIÊN TẬP
Từ tài liệu Android.
Lớp TextInputEditText được cung cấp để sử dụng như một phần tử con của bố cục này. Sử dụng TextInputEditText cho phép TextInputLayout kiểm soát tốt hơn các khía cạnh trực quan của bất kỳ đầu vào văn bản nào. Một ví dụ sử dụng là như vậy:
<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>
TextInputLayout TextInputEditText