打勾显示输入的密码(EditText与setTransformationMethod)
新建一个继承Activity类的EditTextTransformationMethodActivity,并设置布局文件为:edittexttransformationmethod.xml。
首先在布局文件中定义一个EditText和一个CheckBox组件:
<EditText android:id="@+id/edittexttransformationmethod_edit01" android:layout_width="fill_parent" android:layout_height="wrap_content" android:password="true" />
<CheckBox
android:id="@+id/edittexttransformationmethod_cb01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right" android:text="@string/showpassword" /> |
界面效果:
而后在Activity中获取Button和CheckBox这2个组件。此外为CheckBox设置setOnCheckedChangeListener()这个方法。
package lyx.feng.simpletextdemo; ...... public class EditTextTransformationMethodActivity extends Activity { private EditText edit = null; private CheckBox box = null;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setContentView(R.layout.edittexttransformationmethod); this.edit = (EditText) super .findViewById(R.id.edittexttransformationmethod_edit01); this.box = (CheckBox) super .findViewById(R.id.edittexttransformationmethod_cb01); this.box.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
} }); } }
|
最后在onCheckedChanged()方法监听并设置EditText的状态。
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { edit.setTransformationMethod(HideReturnsTransformationMethod .getInstance()); } else { edit.setTransformationMethod(PasswordTransformationMethod .getInstance()); } } |
运行效果:
选中CheckBox结果: