因为项目中用到了这块,所以记录一下!
先看下需要实现的效果:
实际.png
先看下布局排版,RelativeLayout里面放置一个ImageView、一个EditText, 一个CheckBox,用作显示的密码编辑一栏。
下面是xml的布局:
android:layout_marginTop="@dimen/marginSize_10dp"
android:layout_width="match_parent"
android:layout_height="@dimen/height_50dp">
android:layout_centerVertical="true"
android:id="@+id/iv_ct_pwd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="@drawable/ct_login_pwd"
android:textColor="@color/color_gray"
android:textSize="@dimen/tv_16sp" />
android:layout_toLeftOf="@+id/cb_pwd_tips"
android:layout_marginLeft="@dimen/marginSize_10dp"
android:layout_toRightOf="@+id/iv_ct_pwd"
android:id="@+id/et_acc_pwd"
android:layout_width="match_parent"
style="@style/et_style_normal"
android:inputType="textPassword"
android:text=""
android:hint="@string/et_ct_login_hint_pwd"
android:textSize="@dimen/tv_16sp" />
android:layout_marginRight="@dimen/marginSize_5dp"
android:checked="false"
android:id="@+id/cb_pwd_tips"
android:layout_width="wrap_content"
android:layout_height="@dimen/marginSize_30dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:button="@drawable/selector_password"/>
其中CheckBox的@drawable/selector_password样式如下:
这里是2个图标,如下:
icon_pwd_hide.png
icon_pwd_show.png
接下来是具体的代码实现:
cbPwdTips.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
etAccountPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}else {
etAccountPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
}
etAccountPwd.setSelection(etAccountPwd.getText().length());
}
});
自己也是查看网上的设置的明暗文显示方式,也记录一下,
// 方式一:
// 显示明文、暗文
// 选择状态 显示明文--设置为可见的密码
etAccountPwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
//默认状态显示密码--设置文本 要一起写才能起作用 InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD
etAccountPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
// 第二种方式:
// 明文
etAccountPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
// 暗文
etAccountPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
以上就是实现的例子了。
参考文章: