android 控制EditText字符长度[配置控制 代码控制]


   序:此文章主要概要如何控制EditText字符长度,分别从layout的配置和代码实现两方面说明.以备日后之用,也供大家学习.如有不恰当之处还请大家多多指出[红色     标记处为重点].


   一:配置控制

 <EditText
                android:id="@+id/registrationAuthCode_code_ex"
                android:layout_width="fill_parent"
                android:layout_height="@dimen/dip_height_3"
                android:layout_centerVertical="true"
                android:layout_marginLeft="@dimen/dip_spacing_4"
                android:layout_toLeftOf="@id/ic_delete"
                android:layout_toRightOf="@id/usr_icon_iv"
                android:background="@color/transparent"
                android:contentDescription="@string/regcode_codeet"
                android:hint="@string/registrationauthcode_code_hint"
                android:inputType="number"
                android:maxLength="6"
                android:textColor="@color/primary_black"
                android:textColorHint="@color/second_gray"
                android: textSize="@dimen/sp_size_3"/>

 

  二:代码控制

import android.content.Context;
import android.graphics.Color;
import android.text.InputFilter;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.widget.EditText;
/**
* <esEditTxt控件底层实现类>
*
* @FileName
* @author christineRuan
* @date 2013-12-6 上午9:10:59
* @version V1.0 <实现:约束控件最大字符值>
*/
public class ESEditText extends EditText {
//private String encoding = "GBK";
private int maxByteLength = 100; //默认100个字符
public ESEditText(Context context,int maxSize) {
super(context);
this.setTextColor(Color.BLACK);
if(maxSize==-1) //未做maxSize配置
{
maxSize=maxByteLength;
}
init(maxSize);
}
private void init(int maxSize) {
maxByteLength=maxSize;
setFilters(new InputFilter[] { inputFilter }); //设置输入过滤
}
private InputFilter inputFilter = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
try {
int len = 0;
boolean more = false;
do {
SpannableStringBuilder builder = new SpannableStringBuilder( dest).replace(dstart, dend,source.subSequence(start, end));//len = builder.toString().getBytes(encoding).length;
dest).replace(dstart, dend,
source.subSequence(start, end));
//len = builder.toString().getBytes(encoding).length; //字节长度
len = builder.toString().length(); //字符长度
more = len > maxByteLength;
if (more) {
end--;
source = source.subSequence(start, end);
}
} while (more);
return source;
} catch (Exception e) {
return "Exception";
}
}
};
}



你可能感兴趣的:(android 控制EditText字符长度[配置控制 代码控制])