Custom EditText dynamically controls the number of input characters
During development, it is inevitable that the number of characters must be controlled, for example, if a user's name requires you to enter 10 characters (meaning that 10 characters can be entered in English but only five Chinese characters can be entered), the first response may be to set the length of EditText in xml, this situation certainly does not meet our requirements. The following describes your methods.
1. Declare a class to inherit the InputFilter and implement the method in the filter. The following are detailed annotations for readers to take a closer look.
Public class MyLenghtFilter implements InputFilter {
Int nMax = 0; int keep = 0; public MyLenghtFilter (int nMax) {this. nMax = nMax;}/*** below is my understanding */@ Overridepublic CharSequence filter (CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {// end is the length of the dstart character to be entered, by default, when dend re-enters a character, the two lengths are equal. // when the delete character is executed in the input method, dstart displays the length of the deleted character, before dend is deleted, try {keep = nMax-(dest. toString (). getBytes ("GBK "). length-(dend-dstart); if (keep <= 0) {// determine whether the entered character length is greater than or equal to the maximum length return "";} else if (keep> = source. toString (). getBytes ("GBK "). length-start) {// if the length of the input character is smaller than the maximum length, return the input character return null;} else {return source. subSequence (start, (start + keep)/2); // If the input length is greater than the maximum length, extract the previous several characters and output} catch (UnsupportedEncodingException e) {e. printStackTrace ();} return null ;}}
2. The custom EditText is as follows:
public class MyEditText extends EditText {public MyEditText(Context context) {super(context);} public void setFileter(int maxLen){this.setFilters(new InputFilter[]{new MyLenghtFilter(maxLen)});}public MyEditText(Context context, AttributeSet attrs) {super(context, attrs);if(attrs!=null){TypedArray typedArray=context.obtainStyledAttributes(attrs,R.styleable.myEditInfo);setFileter(typedArray.getInt(R.styleable.myEditInfo_maxlen,100));typedArray.recycle();}}}
Custom Attributes are used in this class to set the length of the input in xml.
If there is still a better way to read data, please leave a message to me.