安卓在代码中设置TextView的drawableLeft、drawableRight、drawableTop、drawableBottom,并设置监听
16lz
2021-01-24
TextView的xml文件:
其中 android:digits="@string/rule_edit" 为文本过滤:
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`¬!"£$%^*()~=#{}[];':,./?/*-_+<>@&
在代码中如果要修改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; } }
文章参考于:https://blog.csdn.net/catoop/article/details/39959175
更多相关文章
- Mac Android(安卓)Studio快捷键
- PHP 和 Android(安卓)MD5 加密出来结果是一样的代码
- Android(安卓)顶部状态栏覆盖到应用之上?
- 开发安卓-android使用webview加载网页无法使用js的问题
- [Android(安卓)Pro] 关于BitmapFactory.decodeStream(is)方法无
- Android:不同drawable文件夹的区别
- Android(安卓)提升开发效率工具(Template/Plugin)
- android 之 新浪微博
- Android(安卓)3.0 访问WebService 出现 android.os.NetworkOnMai