java - 更改 editText 字段内的可绘制图像

标签 java android xml android-studio

我正在构建一个密码可见性切换系统(不使用 TextInputLayout)。 它正在工作,但我想在用户单击 EditText 输入字段内的图标时更改图标。

xml

<EditText
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:id="@+id/etPassword"
    android:layout_marginRight="20dp"
    android:inputType="textPassword"
    android:layout_marginLeft="20dp"
    android:layout_marginBottom="20dp"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:background="@drawable/input_border"
    android:drawableRight="@drawable/eye_image"
    android:hint="Your Password" />

eye_image.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item
    android:drawable="@drawable/eye_show"
    android:width="25dp"
    android:height="25dp"
    />
</layer-list>

java代码

password.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            final int DRAWABLE_LEFT = 0;
            final int DRAWABLE_TOP = 1;
            final int DRAWABLE_RIGHT = 2;
            final int DRAWABLE_BOTTOM = 3;
            if(event.getAction() == MotionEvent.ACTION_UP) {
                if(event.getRawX() >= (password.getRight() - password.getCompoundDrawables() 
[DRAWABLE_RIGHT].getBounds().width())) {
                    // your action here
if(password.getTransformationMethod().equals(PasswordTransformationMethod.getInstance())){

                        //Show Password
                       ((ImageView)(view)).setImageResource(R.drawable.eye_show);
password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                        password.setSelection(password.getText().length());
                    }
                    else{
                        //Hide Password
 ((ImageView)(view)).setImageResource(R.drawable.eye_show);
password.setTransformationMethod(PasswordTransformationMethod.getInstance());
                        password.setSelection(password.getText().length());
                    }
               }
            }
            return false;
        }
    });

我收到此错误 - androidx.appcompat.widget.AppCompatEditText 无法转换为 android.widget.ImageView

我只想将 eye_image.xml 可绘制对象中的图像放置在 editText 的右侧,以便在单击时更改为另一个图像

最佳答案

找到了方法,这成功了

editText.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.eye_image2, 0);

关于java - 更改 editText 字段内的可绘制图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59505100/

相关文章:

java - 在 persistence.xml 之外定义 jpa 实体类

java - 获取HTTP请求头信息: Java

android - 索尼智能 watch 2 中的 ListView

android - ListView : TextView with LinkMovementMethod makes list item unclickable?

Java - 如何关闭重置由我的应用程序初始化的套接字并即时重新打开它?在 TCP 或 UDP 中

java - 如何动态生成实例名称?

android - 如何通过estimote android sdk更改estimote beacon的UUID?

xml - XPath 中的.//和//* 有什么区别?

php - 使用 PHP 创建 SOAP 请求 - 如何向 XML 标记添加属性?

Android 编程 - 如何使用代码访问 main.xml 布局中的 [to draw on] XML View