Android入门之EditText(纯Java)
| [日期:2011-09-14] |
来源:Linux社区
作者:mrlixirong |
[字体:大 中 小]
|
- 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);
- }
-
- 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);
- }
-
- 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);
- }
-
- 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("请输入账号:");
- }
-
- 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");
- }
-
- 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) {
-
- if(et.length()>12){
-
- et.setText((et.getText()).subSequence(0, 12));
-
- 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);
- }
- }
