基于状态的ImageButton图标着色

LeD*_*Don 5 android

我目前正在尝试使用当前纯白色的Drawables在某些ImageButton上实现着色。色调颜色应由StateList提供,并应根据按钮的当前状态进行更改。状态列表看起来像:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="#FF0000"/>
    <item android:color="#00FF00" android:state_enabled="false"/>
    <item android:color="#0000FF" android:state_pressed="true" android:state_enabled="true"/>
</selector>
Run Code Online (Sandbox Code Playgroud)

该按钮的布局XML代码段为:

<ImageButton
    android:id="@+id/btnNext"
    style="@style/Widget.AppCompat.Button.Borderless"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="@dimen/vertical_content_padding"
    android:layout_marginEnd="@dimen/horizontal_content_padding"
    android:contentDescription="@string/next"
    android:src="@drawable/ic_chevron_right_white_24dp"
    android:tint="@color/state_btn_tint_light"/>
Run Code Online (Sandbox Code Playgroud)

选择并正确显示了颜色状态列表中的默认色调。但是禁用或按下按钮不会在所有Icon上触发任何颜色更改。我也尝试使用setImageTintList实用地设置它。

Sha*_*hin 1

我将简化我的答案。希望有帮助。您始终可以在colors.xml 中输入您想要的任何颜色,对吗?所以让我们使用它吧。

您可以像这样创建您想要的颜色的整数数组列表

integer[] colors = new integer[]{R.color.white, R.color.black, ...};
Run Code Online (Sandbox Code Playgroud)

现在 imageButtons 可以采用这样的背景色调:

imagebutton.setImageTintList(ColorStateList.valueOf(ContextCompat.getColor(mContext,R.color.white)));
Run Code Online (Sandbox Code Playgroud)
  1. 现在让我们把它们和动画放在一起,创建动画方法:

integer[] colors = new integer[]{R.color.white, R.color.black, ...};
Run Code Online (Sandbox Code Playgroud)

  1. 现在,在您的活动中,您可以像这样实现它:

imagebutton.setImageTintList(ColorStateList.valueOf(ContextCompat.getColor(mContext,R.color.white)));
Run Code Online (Sandbox Code Playgroud)