EditText提供了密码输入类型,inputType=”textPassword”,但“……”这样的符号也难以让输入着确定自己输入了啥东西。若能体贴地提供显示密码的选择,那就完美了。
主要知识点:EditText 提供了两个方法:
隐藏的方法——HideReturnsTransformationMethod.getInstance()
显示的方法——PasswordTransformationMethod.getInstance()
效果图:
默认输入:‘
勾选了显示密码的效果图:
代码块:
布局activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="@string/et_tip" />
<EditText
android:id="@+id/et_pwd"
android:layout_width="match_parent"
android:layout_height="55dp"
android:inputType="textPassword"
android:hint="@string/et_tip"/>
<CheckBox
android:id="@+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/show_pws"/>
</LinearLayout>
MainActivity.java
package com.example.etdisplaypassword;
import android.app.Activity;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
public class MainActivity extends Activity {
private EditText et_Pwd;
private CheckBox checkBox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_Pwd = (EditText) findViewById(R.id.et_pwd);
checkBox = (CheckBox) findViewById(R.id.checkbox);
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton cb, boolean arg1) {
if (cb.isChecked()) {
et_Pwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
} else {
et_Pwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
}
}
});
}
}
保存运行,结果完美!