限制EditText输入字数
1、main_activity.xml
package forrest.foreditlimit;import android.os.Bundle;import android.app.Activity;import android.text.Editable;import android.text.TextWatcher;import android.view.Menu;import android.widget.EditText;import android.widget.TextView;public class MainActivity extends Activity {private EditText et;private TextView tv;private int limitNum = 10;protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);init();setListener();}private void setListener() {et.addTextChangedListener(new TextWatcher() {public void onTextChanged(CharSequence s, int start, int before, int count) {}public void beforeTextChanged(CharSequence s, int start, int count, int after) {}public void afterTextChanged(Editable s) {if (s.length() > limitNum) {// 不能输入s.delete(limitNum, limitNum+1);et.setText(s);et.setSelection(limitNum);} else {tv.setText("还可输入" + (limitNum - s.length()) + "字");}}});}private void init() {et = (EditText) findViewById(R.id.et);tv = (TextView) findViewById(R.id.tv);}}