Android EditText java 设置 maxLength
生活随笔
收集整理的這篇文章主要介紹了
Android EditText java 设置 maxLength
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
我們在開發(fā)過程,經(jīng)常會(huì)遇到EditText 設(shè)置可輸入內(nèi)容長度,但是發(fā)現(xiàn)java代碼沒有set方法,通過源碼,我們發(fā)現(xiàn)InputFilter的妙用所在。
在TextView中我們發(fā)現(xiàn)maxLength默認(rèn)值為-1,并且當(dāng)mxLength大于等于0才會(huì)設(shè)置LengthFilter
if (maxlength >= 0) {setFilters(new InputFilter[] { new InputFilter.LengthFilter(maxlength) }); } else {setFilters(NO_FILTERS); }接下來,我們查看一下 InputFilter.LengthFilter 中代碼
/*** This filter will constrain edits not to make the length of the text* greater than the specified length.*/public static class LengthFilter implements InputFilter {@UnsupportedAppUsageprivate final int mMax;public LengthFilter(int max) {mMax = max;}public CharSequence filter(CharSequence source, int start, int end, Spanned dest,int dstart, int dend) {int keep = mMax - (dest.length() - (dend - dstart));if (keep <= 0) {return "";} else if (keep >= end - start) {return null; // keep original} else {keep += start;if (Character.isHighSurrogate(source.charAt(keep - 1))) {--keep;if (keep == start) {return "";}}return source.subSequence(start, keep);}}/*** @return the maximum length enforced by this input filter*/public int getMax() {return mMax;}}那么我們EditText可以:
editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(maxlength) });來實(shí)現(xiàn),java代碼設(shè)置 最大輸入內(nèi)容長度。
InputFilter可以實(shí)現(xiàn)很多功能。
總結(jié)
以上是生活随笔為你收集整理的Android EditText java 设置 maxLength的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java未来的应用前景
- 下一篇: 标准的弯腿90度图片_桥架直角90度做法