Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

android - How can I change colors in my StateListDrawable?

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" />

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

How can I do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
     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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...