Mukesh Y.
Mukesh Y.

Reputation: 949

Android : How to change color of Drawable selector programmatically depends on condition?

I have a button

<Button
 android:id="@+id/loginButton"
 android:layout_width="35dp"
 android:layout_height="35dp"
 android:background="@drawable/button_shape"
 android:text="@string/login"
 android:textColor="#ffffff"
 android:textSize="12sp" />

following is button_shape.xml

<?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/button_gradient_login" />
<item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/button_gradient_login" />
<item>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">
        <size android:height="16dp" />
        <solid android:color="@color/valid_btn_clr"></solid>
        <corners android:radius="10dp"></corners>
    </shape>
</item>

Following is button_gradient_login.xml

<?xml version="1.0" encoding="utf-8"?>
   <layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
   <shape xmlns:android="http://schemas.android.com/apk/res/android">
        <gradient android:angle="360" android:startColor="@color/red"     android:endColor="@color/green"/>
        <corners android:radius="4dp"></corners>
    </shape>
</item></layer-list>

Now I want to change the background color of button_shape.xml and on press start and end color of button_gradient_login.xml at run time depens on my conditions

Upvotes: 1

Views: 2787

Answers (1)

Jay
Jay

Reputation: 111

You can make drawable selector programatically Here is code for state_activated. Please refer below code.

        GradientDrawable gradientDrawable = new GradientDrawable();
        gradientDrawable.setStroke((int) context.getResources().getDimension(R.dimen.dp1), Color.BLACK);
        gradientDrawable.setCornerRadius(context.getResources().getDimension(R.dimen.dp5));
        gradientDrawable.setColor(((MainActivity) context).getBgColor());

        GradientDrawable gradientDrawableDefault = new GradientDrawable();
        gradientDrawableDefault.setStroke((int) context.getResources().getDimension(R.dimen.dp1), Color.BLACK);
        gradientDrawableDefault.setCornerRadius(context.getResources().getDimension(R.dimen.dp5));
        gradientDrawableDefault.setColor(Color.WHITE);

        StateListDrawable stateListDrawable = new StateListDrawable();
        stateListDrawable.addState(new int[]{android.R.attr.state_activated}, gradientDrawableDefault); // if activated true
        stateListDrawable.addState(StateSet.WILD_CARD, gradientDrawable); // rest all the state

Upvotes: 10

Related Questions