手机号 3-4-4控制
package com.gx_school.util; import com.gx_school.activity.ArriveActivity; import android.content.Context; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; 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) { String str = s.toString(); if(str.length() > 13){ str = str.substring(0, 13); Log.v("result", str); editText.setText(str); editText.setSelection(13); return; } if((str.length() == 3 || str.length() == 8) && str.charAt(str.length() - 1) != ‘-‘ && before < count){ str += "-"; editText.setText(str); editText.setSelection(str.length()); return; } //删除时去掉横线 if((str.length() == 3 || str.length() == 8) && str.charAt(str.length() - 1) != ‘-‘ && before > count){ str = str.substring(0, str.length() - 1); editText.setText(str); editText.setSelection(str.length()); return; } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { Log.v("result", "beforeTextChanged " + s.toString()); } @Override public void afterTextChanged(Editable s) { Log.v("result", "afterTextChanged " + s.toString()); } }); } /** * 限制输入的长度 * @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 } }); } }
引用
phoneNum = (EditText) findViewById(R.id.et_arriver_phoneNumber);
new EditTextWatcher(ArriveActivity.this).setPricePoint(phoneNum);
本文出自 “爬过山见过海” 博客,请务必保留此出处http://670176656.blog.51cto.com/4500575/1704166
原文地址:http://670176656.blog.51cto.com/4500575/1704166