限制输入字符个数:
public class EditTextWithLimitChar extends EditText { private int NUM_MAX_CHAR = Integer.MAX_VALUE; // 默认字数无限制 private int sum = 0; // 记录已经输入的总共的字符 private CharSequence temp; private int editStart; private int editEnd; /** * 设置最大限制字符的个数 * * @param limits */ public void setLimits(int limits) { NUM_MAX_CHAR = limits; } public EditTextWithLimitChar(Context context) { super(context); // TODO Auto-generated constructor stub init(); } public EditTextWithLimitChar(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // TODO Auto-generated constructor stub init(); } public EditTextWithLimitChar(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub init(); } private void init() { addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub temp = s; } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub editStart = getSelectionStart(); editEnd = getSelectionEnd(); Log.d("TAG", "editStart=" + editStart + ", " + "editEnd=" + editEnd); if (temp.length() > NUM_MAX_CHAR) { Toast.makeText(getContext(), "你输入的字数已经超过了限制!", Toast.LENGTH_SHORT).show(); s.delete(editStart - 1, editEnd); int tempSelection = editStart; setText(s); setSelection(tempSelection); } } }); } @Override protected void finalize() throws Throwable { super.finalize(); } }
时间: 2024-10-05 18:07:29