版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Snow_Ice_Yang/article/details/81778599
TextView的xml文件:
<AutoCompleteTextView
android:id="@+id/et_setpwd_userpwd"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginTop="54dp"
android:background="@null"
android:digits="@string/rule_edit"
android:drawableRight="@drawable/password"
android:hint="@string/input_password"
android:inputType="textPassword"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:singleLine="true"
android:textSize="16sp" />
其中 android:digits="@string/rule_edit" 为文本过滤:
<string name="rule_edit">0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`¬!"£$%^*()~=#{}[];':,./?/*-_+<>@&</string>
在代码中如果要修改drawableRight设置的图片可以使用API
void android.widget.TextView.setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom)
Drawable可以通过 Drawable rightDrawable = getResources().getDrawable(R.drawable.icon_new); 得到。
但是API提示,setCompoundDrawables() 调用的时候,Drawable对象必须调用setBounds(int left, int top, int right, int bottom)方法,于是我们加一行代码就可以了。
Drawable drawableSee = getResources().getDrawable(R.drawable.password_see);
drawableSee.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
adtUserPwd.setCompoundDrawables(null, null, drawableSee, null);
如若为drawableRight设置监听:
adtUserPwd.setOnTouchListener(new onTounchListener());
onTounchListener()代码如下:
private class onTounchListener implements View.OnTouchListener {
@Override
public boolean onTouch(View v, MotionEvent event) {
// et.getCompoundDrawables()得到一个长度为4的数组,分别表示左右上下四张图片
Drawable drawable = adtUserPwd.getCompoundDrawables()[2];
//如果右边没有图片,不再处理
if (drawable == null)
return false;
//如果不是按下事件,不再处理
if (event.getAction() != MotionEvent.ACTION_UP)
return false;
if (event.getX() > adtUserPwd.getWidth()
- adtUserPwd.getPaddingRight()
- drawable.getIntrinsicWidth()) {
if (!displayPassWord) {
Drawable drawableSee = getResources().getDrawable(R.drawable.password_see);
drawableSee.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
adtUserPwd.setCompoundDrawables(null, null, drawableSee, null);
//隐藏密码
adtUserPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
} else {
Drawable drawableSee = getResources().getDrawable(R.drawable.password);
drawableSee.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
adtUserPwd.setCompoundDrawables(null, null, drawableSee, null);
//显示密码
adtUserPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
}
displayPassWord = !displayPassWord;
}
return false;
}
}