Android 輸入框限制字元輸入數,android輸入框字元
有時候對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>