小项目经验总结(1)androidEditText字符串限制本来是项目要用到,发现网上有很多类似的代码了。思路也都差不
小项目经验总结(1)android EditText字符串限制
本来是项目要用到,发现网上有很多类似的代码了。思路也都差不多
利用监视器TextWatcher?
?
如果往edittext输入的的字符串大于10
?
那么就设置edittext的gettext为0到10
public class EditViewFontMax {protected int num;public EditText et_content;public void num(EditText et, int n) {this.et_content = et;this.num = n;et_content.addTextChangedListener(new TextWatcher() {private CharSequence temp;private int selectionStart;private int selectionEnd;@Overridepublic void onTextChanged(CharSequence s, int start, int before,int count) {temp = s;System.out.println("s=" + s);}@Overridepublic void beforeTextChanged(CharSequence s, int start, int count,int after) {}@Overridepublic void afterTextChanged(Editable s) {int number = num - s.length();// tv_num.setText("" + number);selectionStart = et_content.getSelectionStart();selectionEnd = et_content.getSelectionEnd();// System.out.println("start="+selectionStart+",end="+selectionEnd);if (temp.length() > num) {s.delete(selectionStart - 1, selectionEnd);int tempSelection = selectionStart;et_content.setText(s);et_content.setSelection(tempSelection);// 设置光标在最后}}});}}??
?
?
