最近公司新开了一个项目,之前的项目做完也没有做过记录,很多东西都找不到了,为了以后能够方便查阅项目资料,还是写一下博客记录一下吧。
之前做的项目中用户登录模块都是用的验证码以及第三方登录,这次BOSS要求用户名密码登录,功能设计密码可见与不可见,只能重新写登录模块了。
密码的可见与不可见是很好实现的, EditText提供了方法去设置:
设置密码可见
edtLoginPw.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
设置密码不可见
edtLoginPw.setTransformationMethod(PasswordTransformationMethod.getInstance());
但是,总得要有条件去触发执行这些方法吧,于是密码输入框后有了一个小眼睛似的图标来提醒用户点击可以查看密码,图标在按下与松开时切换图标显示
代码:
imgShowLoginPwd.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP://松开事件发生后执行代码的区域
Log.e(TAG,"密码不可见");
imgShowLoginPwd.setImageResource(R.drawable.icon_pwd_hind);
edtLoginPw.setTransformationMethod(PasswordTransformationMethod.getInstance());
break;
case MotionEvent.ACTION_DOWN://按住事件发生后执行代码的区域
Log.e(TAG,"密码可见");
imgShowLoginPwd.setImageResource(R.drawable.icon_pwd_show);
edtLoginPw.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
break;
default:
break;
}
return true;
}
});
注意 onTouch方法中返回值应修改为true 否则当前图标的按压事件中只能消费MotionEvent.ACTION_DOWN事件,而MotionEvent.ACTION_UP事件将不消费,
你的图标只能显示为按下后的样子,松开后也不会恢复
如果不需要监听事件,那么只需要自己写一个xml文件,将其设置为相应控件的背景即可。
控件:
<Button
android:layout_width="match_parent"
android:layout_height="@dimen/btn_commit_height"
android:textSize="@dimen/text_size_18"
android:layout_marginTop="20dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
style="?android:borderlessButtonStyle"
android:background="@drawable/btn_commit"
android:text="提交"/>
xml文件:btn_commit
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/btn_commit_02" android:state_pressed="true"/>
<item android:drawable="@drawable/btn_commit_01" android:state_pressed="false"/>
<item android:drawable="@drawable/btn_commit_01"/>
</selector>
btn_commit_01与btn_commit_02就是你自己写的按下与松开的两种样式了