新建一个Android项目,在main.xml中输入如下代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/msg"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="请输入密码" />
<EditText
android:id="@+id/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:password="true"/>
<CheckBox
android:id="@+id/show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="显示密码"/>
</LinearLayout>
在MingWenActivity.java中输入如下代码(注意不同的包,否则会报错):
package com.tarena.mingwen;
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.CheckBox;
import android.widget.EditText;
public class MingWenActivity extends Activity {
private EditText password = null;
private CheckBox show = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.main);
this.password = (EditText) super.findViewById(R.id.password);
this.show = (CheckBox) super.findViewById(R.id.show);
this.show.setOnClickListener(new OnClickListenerImpl());
}
private class OnClickListenerImpl implements OnClickListener{
public void onClick(View v) {
if(MingWenActivity.this.show.isChecked()){ //如果被选中,则采用明文显示
MingWenActivity.this.password
.setTransformationMethod(HideReturnsTransformationMethod
.getInstance()); //将文本框的内容设置为明文的形式显示
}
else{//否则采用密文的方式显示
MingWenActivity.this.password
.setTransformationMethod(PasswordTransformationMethod
.getInstance()); //将文本框的内容设置为密文的形式显示
}
}
}
}