How to change colors in my StateListDrawable?

I have the following button selector (with two 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 indicates the background as the selector described above:

 <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 colors for both states from code when loading Activity.

How can i do this?

+7
android android-layout xamarin xamarin.android android-ui
source share
1 answer
  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 course, it can be useful.

+19
source share

All Articles