更改分配给以编程方式着色的选择器

Change selector assigned to tint programmatically

我已经为我的 ImageButton 的色调设置了一个可绘制对象,因此当按钮启用或禁用时图标的颜色会自动更改,之后是否有任何方法可以通过编程方式更改色调以便我保持相同的行为只是启用和禁用状态的颜色不同?

my_layout.xml的内容:

<ImageButton
    android:id="@+id/button_minus"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="2"
    android:background="@color/default_button_background"
    android:tint="@drawable/button_tint_color"
    app:srcCompat="@drawable/ic_remove_24px" />

button_tint_color.xml内容:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_enabled="false"
        android:color="@color/icon_tint_disable_color" />

    <item
        android:color="@color/icon_tint_enable_color" />
</selector>

然后在我的代码中,我可以执行 buttonMinus.setEnabled(true)buttonMinus.setEnabled(false) 并且图标颜色会自动更改。有没有办法以编程方式为启用颜色或禁用颜色中的一种或两种设置不同的颜色?

我认为你可以使用这样的东西:

if(buttonMinus.isEnabled()){
//With button enabled
yourIcon.setItemIconTintList(ColorStateList.ValueOf(yourColor));
}else{...}

到目前为止我发现的最佳方法是以编程方式制作一个新的颜色状态列表并将其分配给按钮,哎呀,目标是避免以编程方式设置颜色等视觉属性...

        ColorStateList buttonStates = new ColorStateList(
                new int[][] {
                        { -android.R.attr.state_enabled },
                        {}
                },
                new int[] {
                        Color.RED,
                        Color.BLUE
                }
        );

        buttonMinus.setImageTintList(buttonStates);