Limit the number of characters in the Android input box
Sometimes there is a limit on the number of characters entered in the Android input box, and the number of characters entered is displayed. You can achieve this by using the following methods:
1. subdefinition LimitNumEditText inherits EditText
Import android. content. context; import android. content. res. typedArray; import android. telephony. smsMessage; import android. text. editable; import android. text. inputFilter; import android. text. textWatcher; import android. util. attributeSet; import android. widget. editText; import us. pinguo. cc. r;/*** Created by crab on 15-3-18. */public class LimitNumEditText extends EditText {private int mMaxLength; private OnTextCountChangeListener listener; public LimitNumEditText (Context context) {this (context, null);} public LimitNumEditText (Context context, AttributeSet attrs) {super (context, attrs); TypedArray typedArray = context. obtainStyledAttributes (attrs, R. styleable. limitNumEditText); mMaxLength = typedArray. getInt (R. styleable. limitNumEditText_maxLength,-1); typedArray. recycle (); if (m MaxLength> = 0) {setFilters (new InputFilter [] {new InputFilter. lengthFilter (mMaxLength)});} else {setFilters (new InputFilter [0]);} addTextChangedListener (null );} /*** @ return limit the maximum number of characters entered */public int getLimitLength () {return mMaxLength;} @ Override public void addTextChangedListener (final TextWatcher watcher) {TextWatcher inner = new TextWatcher () {@ Override public void beforeTextChanged (C HarSequence s, int start, int count, int after) {if (watcher! = Null) {watcher. beforeTextChanged (s, start, count, after) ;}@ Override public void onTextChanged (CharSequence s, int start, int before, int count) {int [] params = SmsMessage. calculateLength (s, false); int use = params [1]; if (mMaxLength> = 0 & mTextCountChangeListener! = Null) {mTextCountChangeListener. onTextCountChange (use, mMaxLength);} if (watcher! = Null) {watcher. onTextChanged (s, start, before, count) ;}@override public void afterTextChanged (Editable s) {if (watcher! = Null) {watcher. afterTextChanged (s) ;}}; super. addTextChangedListener (inner);} public LimitNumEditText (Context context, AttributeSet attrs, int defStyle) {super (context, attrs, defStyle);} public void listener (OnTextCountChangeListener listener) {mTextCountChangeListener = listener ;} /*** listen for character changes in the input box */public interface OnTextCountChangeListener {/***** @ param use the size of the input character likes * @ param total limit the number of input online */public void onTextCountChange (int use, int total );}