如何更改TextInputLayout

时间:2019-06-20 00:38:57

标签: android android-textinputlayout

当状态为焦点时,我正在尝试更改startIconDrawable的{​​{1}}属性的颜色,但是我找不到解决方法!

TextInputLayout

我试图通过创建包含以下内容的<com.google.android.material.textfield.TextInputLayout android:id="@+id/Login_Fragment_Email_Text_Input" android:layout_width="match_parent" android:layout_height="60dp" android:layout_marginStart="24dp" android:layout_marginTop="40dp" android:layout_marginEnd="24dp" android:background="@drawable/text_input_top_selector" android:paddingTop="8dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/Login_Fragment_Logo_Image" app:startIconDrawable="@drawable/profile" app:startIconTint="@drawable/icon_color_edit_text_selector"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/Login_Fragment_Email_Edit_Text" android:focusableInTouchMode="true" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginBottom="-8dp" android:hint="@string/email" android:paddingBottom="16dp" android:theme="@style/CustomEditText" /> </com.google.android.material.textfield.TextInputLayout> 来做到这一点

icon_color_edit_text_selector.xml

但是它仅显示默认颜色<selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:color="@color/colorAccent" android:state_focused="true" /> <item android:color="@color/iconColor" android:state_focused="false"/> </selector>

1 个答案:

答案 0 :(得分:1)

您可以使用startIconTint属性:

https://developer.android.com/reference/com/google/android/material/textfield/TextInputLayout.html#attr_TextInputLayout_startIconTint


或者如果要在代码中执行此操作,则可以使用setStartIconTintList:

https://developer.android.com/reference/com/google/android/material/textfield/TextInputLayout.html#setStartIconTintList(android.content.res.ColorStateList)

更新
若要仅在编辑文本具有焦点时更改颜色,应在视图上添加焦点监听器,但是这会引起问题,因为文本输入布局不会获得焦点。但是,取而代之的是TextInputEditText。因此,您应该改为在文本输入edittext的实例中添加焦点监听器。这是一个示例:

// You could simplify this with lambda's
// The variable names i used here matches the id's you have shown on your xml
edit1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        textInputLayout.setStartIconTintList(hasFocus ? ColorStateList.valueOf(Color.RED) : ColorStateList.valueOf(Color.BLUE));
    }
});