0

我正在尝试更改状态聚焦时startIconDrawable属性的颜色,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>

但它只显示默认颜色,即state_focused ="false"

4

1 回答 1

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));
    }
});
于 2019-06-20T01:06:22.833 回答