如何更改 StateListDrawable 中的颜色? [英] How can I change colors in my StateListDrawable?

查看:29
本文介绍了如何更改 StateListDrawable 中的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下按钮选择器(有 2 个状态,常规和按下):

I have the following selector for a button (with 2 states, regular and pressed):

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" >
 <shape>
  <solid
      android:color="#3498DB" />
  <stroke
      android:width="1dp"
      android:color="#2980B9" />
  <corners
      android:radius="0dp" />
  <padding
      android:left="12dp"
      android:top="12dp"
      android:right="12dp"
      android:bottom="12dp" />
 </shape>
</item>
<item>
 <shape>
  <solid
      android:color="#2980B9" />
  <stroke
      android:width="1dp"
      android:color="#2980B9" />
  <corners
      android:radius="0dp" />
  <padding
      android:left="12dp"
      android:top="12dp"
      android:right="12dp"
      android:bottom="12dp" />
 </shape>
</item>
</selector>

我的按钮具有以下指定背景作为上述选择器的内容:

My button has the following which specifies the background as the above selector:

<Button
  android:id="@+id/button_LaunchShiftsGame"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:text="@string/ShiftsMode"
  android:background="@drawable/selector_Button"
  style="@style/Button_Text" />

我需要在 Activity 加载时通过代码访问和更改两种状态的颜色.

I need to access and change the colors for both states from code when the Activity loads.

我该怎么做?

推荐答案

     StateListDrawable gradientDrawable = (StateListDrawable) inflatedView.getBackground();
    DrawableContainerState drawableContainerState = (DrawableContainerState) gradientDrawable.getConstantState();
    Drawable[] children = drawableContainerState.getChildren();
    LayerDrawable selectedItem = (LayerDrawable) children[0];
    LayerDrawable unselectedItem = (LayerDrawable) children[1];
    GradientDrawable selectedDrawable = (GradientDrawable) selectedItem.getDrawable(0);
    GradientDrawable unselectedDrawable = (GradientDrawable) unselectedItem.getDrawable(0);
    selectedDrawable.setStroke(STORKE_SIZE, NOTIFICATION_COLOR);
    unselectedDrawable.setStroke(STORKE_SIZE, NOTIFICATION_COLOR);

我用这个来改变笔画,它很有帮助.

I used this to change the stroke, it can be helpfull.

这篇关于如何更改 StateListDrawable 中的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆