这里介绍EditText的简单使用方法,EditText是一个文本输入框,我们在与用户交互的时候常常会用到,比如登录、注册等需要用户输入信息的地方。 先看看例子的效果图: 从上到下依次是一个TextView,用于显示输入的字符串;一个EditText,用于输入字符串;一个CheckBox,用于控制隐藏显示输入字符;最后是一个Button,用于控制TextView显示输入的字符串。下面是布局XML代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView android:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<EditText android:id="@+id/et"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<CheckBox android:id="@+id/cb"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="显示或隐藏密码"
/>
<Button android:id="@+id/bt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="显示输入的字符串"
/>
</LinearLayout>
程序代码:
package com.pocketdigi.edit;
import android.app.Activity;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;
public class main extends Activity {
/** Called when the activity is first created. */
EditText et;
CheckBox cb;
TextView tv;
Button bt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
et=(EditText)findViewById(R.id.et);
et.setTransformationMethod(PasswordTransformationMethod.getInstance());
//默认隐藏状态,不显示输入的字符,如果默认不隐藏则删除上面这行
cb=(CheckBox)findViewById(R.id.cb);
tv=(TextView)findViewById(R.id.tv);
bt=(Button)findViewById(R.id.bt);
bt.setOnClickListener(show);
cb.setOnCheckedChangeListener(listener);
}
OnCheckedChangeListener listener=new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
et.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
//如果选中,显示密码
}else{
et.setTransformationMethod(PasswordTransformationMethod.getInstance());
//否则隐藏密码
}
}
};
OnClickListener show=new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
tv.setText(et.getText());
//点Button后,TextView显示输入的字符串
}
};
}