【问题标题】:Change selector assigned to tint programmatically以编程方式更改分配给色调的选择器
【发布时间】:2019-02-14 09:31:05
【问题描述】:

我已经为 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) 并且图标颜色会自动更改。有没有办法以编程方式为启用颜色或禁用颜色中的一种或两种设置不同的颜色?

【问题讨论】:

  • 您需要以编程方式创建(或从按钮获取并编辑)StateListDrawable
  • 是否无法更改分配的可绘制对象或应用具有不同值的“icon_tint_disable_color”和“icon_tint_enable_color”常量的不同主题?

标签: android android-drawable


【解决方案1】:

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

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

        buttonMinus.setImageTintList(buttonStates);

【讨论】:

  • 为什么要在 android.R.attr.state_enabled 上减号?
  • @AtulGupta 这就是你如何获得禁用状态
  • 奇怪的是,在我的情况下它没有 - 符号。
【解决方案2】:

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

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

【讨论】:

  • 不,目标是避免以编程方式设置按钮视觉属性,以避免代码中的噪音和错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-02
相关资源
最近更新 更多