标签:edittext
监听EditText输入的长度,控制合法数据录入 package com.gx_school.model; import android.content.Context; import android.text.Editable; import android.text.TextWatcher; import android.widget.EditText; public class EditTextWatcher{ private Context mContext; public EditTextWatcher(Context context){ mContext = context; } /** * 限制输入小数点后两位 * @param editText */ public void setPricePoint(final EditText editText) { editText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (s.toString().contains(".")) { if (s.length() - 1 - s.toString().indexOf(".") > 2) { s = s.toString().subSequence(0, s.toString().indexOf(".") + 3); editText.setText(s); editText.setSelection(s.length()); } } if (s.toString().trim().substring(0).equals(".")) { s = "0" + s; editText.setText(s); editText.setSelection(2); } if (s.toString().startsWith("0") && s.toString().trim().length() > 1) { if (!s.toString().substring(1, 2).equals(".")) { editText.setText(s.subSequence(0, 1)); editText.setSelection(1); return; } } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } }); } /** * 限制输入的长度 * @param editText * @param len */ public void setEditLength(final EditText editText, final int len) { editText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if(s.toString().length() > len){ String str = s.toString().subSequence(0, len).toString(); editText.setText(str); editText.setSelection(str.length()); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } }); } } 使用方法 private EditText edtTransFee; edtTransFee = (EditText) findViewById(R.id.tv_arriver_trans_fee); new EditTextWatcher(this).setPricePoint(edtTransFee);
本文出自 “爬过山见过海” 博客,请务必保留此出处http://670176656.blog.51cto.com/4500575/1650938
标签:edittext
原文地址:http://670176656.blog.51cto.com/4500575/1650938