import android.app.Activity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.widget.*; public class EditTextTest extends Activity { private LinearLayout mainLayout=null; private RelativeLayout layout=null; private TextView tv1=null; //标题 private TextView tv2=null; //可输入剩余字符数 private EditText et=null; //输入框 public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mainLayout_init(); setContentView(mainLayout); } /*mainLayout初始化*/ void mainLayout_init(){ mainLayout=new LinearLayout(this); LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(-1, -1); mainLayout.setLayoutParams(lp); mainLayout.setOrientation(LinearLayout.VERTICAL); layout_init(); mainLayout.addView(layout); et_init(); mainLayout.addView(et); } /*layout1初始化*/ void layout_init(){ layout=new RelativeLayout(this); RelativeLayout.LayoutParams lp=new RelativeLayout.LayoutParams(-1, -2); layout.setLayoutParams(lp); tv1_init(); layout.addView(tv1); tv2_init(); layout.addView(tv2); } /*tv11初始化*/ void tv1_init(){ tv1=new TextView(this); RelativeLayout.LayoutParams lp=new RelativeLayout.LayoutParams(-2, -2); lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT); tv1.setLayoutParams(lp); tv1.setTextSize(30); tv1.setText("请输入账号:"); } /*tv12初始化*/ void tv2_init(){ tv2=new TextView(this); RelativeLayout.LayoutParams lp=new RelativeLayout.LayoutParams(-2, -2); lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); tv2.setLayoutParams(lp); tv2.setTextSize(30); tv2.setText("12"); } /*et1初始化*/ void et_init(){ et=new EditText(this); LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(-1,-2); et.setLayoutParams(lp); et.setSingleLine(true); //字符变化监听 TextWatcher tw=new TextWatcher(){ public void afterTextChanged(Editable s) { //限制输入,最多允许输入12个 if(et.length()>12){ //截取字符串,舍弃最后一个 et.setText((et.getText()).subSequence(0, 12)); //设置光标。由于用setText函数会导致光标复位,所以重新设置光标到末尾 et.setSelection(12); } //显示剩余可输入字符数 tv2.setText(String.valueOf(12-et.length())); } public void beforeTextChanged(CharSequence s, int start, int count,int after) {} public void onTextChanged(CharSequence s, int start, int before,int count) {} }; et.addTextChangedListener(tw); } }