Android 自定义 EditText 带有左侧图标,可以更改焦点上的颜色并在编辑文本不为空时保持焦点上的图标颜色?

标签 android android-layout android-edittext

我在寻找什么?

I want to keep the icon drawable on focus when the editTextView is not empty

我有一个自定义的editTextView,它有一个左侧可绘制图标,并且当editTextView处于onFocus时,我设法更改了可绘制图标,问题是当我尝试时当 editTextVw 不为空时,保留 onFocus Drawable,什么也不会发生,就像只有 setOnFocusChangeListener 可以正常工作。

Here's the Images from the test EditTextView App :

第一张图片是当editTextView不处于焦点时

the first image is when the editTextVw is not onFocus

第二张图片是当 editTextVw 处于 onFocus 时

the second image is when the editTextVw is onFocus

and here's the code i used for changing the drawable when onFocus:

editTextVw2 = (EditText) findViewById(R.id.editTextVw2);
   editTextVw2.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                Drawable focus_icon = context.getResources().getDrawable(R.drawable.user_focus_18dp); //the focus_icon image
                focus_icon = DrawableCompat.wrap(focus_icon);
                editTextVw2.setCompoundDrawablesWithIntrinsicBounds(focus_icon, null, null, null);
            } else {
                Drawable default_icon = context.getResources().getDrawable(R.drawable.user_18dp); //the default image
                default_icon = DrawableCompat.wrap(default_icon);
                editTextVw2.setCompoundDrawablesWithIntrinsicBounds(default_icon, null, null, null);
            }
        }
    });

-- 我尝试添加一个方法来检查 editTextVw 是否不为空并再次应用

  Drawable focus_icon = context.getResources().getDrawable(R.drawable.user_focus_18dp); //the focus_icon image
            focus_icon = DrawableCompat.wrap(focus_icon);
            editTextVw2.setCompoundDrawablesWithIntrinsicBounds(focus_icon, null, null, null);

但它保持不变。

What should be the quick solution for this ?

最佳答案

您还需要将 TextChangedListener 添加到您的编辑文本中

editTextVw2.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {
            if (s.text.toString().isNotEmpty){
                //change color icon
            }

        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        }
    })

关于Android 自定义 EditText 带有左侧图标,可以更改焦点上的颜色并在编辑文本不为空时保持焦点上的图标颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53825036/

相关文章:

javascript - 如何等待 Android 上的元标记 "user-scalable=no"准备就绪?

android - 如何从 ListView 中获取值

android - 如何在用户键入时用不同的注释替换一个注释(将 “space” 替换为 “-”

android - AlertDialog 中的 EditText 始终为 null

android - 在 Google Glass 上使用 libstreaming 时找不到 Stsd 框

android - 动态改变Textview大小

java - ParseObject 数组可以容纳的对象数量是否有限制?

android - 如何以编程方式从布局中获取 subview [来自 R.layout 资源]

android - 安卓输入错误

Android 显示/隐藏小部件调整大小填充父级