有时候对Android的输入框有字符输入数量的限制,而且显示字符输入的数量。通过下面方式能够实现:

1.自己定义LimitNumEditText继承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 mTextCountChangeListener;

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 (mMaxLength >= 0) {
setFilters(new InputFilter[]{new InputFilter.LengthFilter(mMaxLength)});
} else {
setFilters(new InputFilter[0]);
}
addTextChangedListener(null);
}
/**
* @return 返回限制输入的最大字符数量
*/
public int getLimitLength(){
return mMaxLength;
}
@Override
public void addTextChangedListener(final TextWatcher watcher) {
TextWatcher inner=new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence 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 setOnTextCountChangeListener(OnTextCountChangeListener listener){
mTextCountChangeListener=listener;
}
/**
* 监听输入框字符变化
*/
public interface OnTextCountChangeListener{
/**
*
* @param use 输入字符赞据的大小
* @param total 限制输入数量的上线
*/
public void onTextCountChange(int use, int total);
}


2.改动res/values/attrs.xml文件,添加例如以下行


  <declare-styleable name="LimitNumEditText">

        <attr name="maxLength" format="integer" />

    </declare-styleable>


3.在布局文件里使用


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:algnText="http://schemas.android.com/apk/res-auto"
android:background="#FFFFFF"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.crab.mycameratest.LimitNumEditText
algnText:maxLength="20"
android:id="@+id/id_edit_text_test"
android:layout_width="match_parent"
android:layout_height="50dp"/>
</LinearLayout>