javaandroidandroid-drawable

Android - Change drawable color in runtime


I''m using a drawable for the cells in my table layout in my Android application. I want to change the cell colors on click event. Is it possible to change the color of the drawable in run time. my drawable is,

<?xml version="1.0" encoding="utf-8"?>
<shape
  xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape= "rectangle"  >
        <solid android:color="#FFFFFF"/>
        <stroke android:width="1dp"  android:color="#483D8B"/>
</shape>

And I want to change the white color "#FFFFFF" with the click event. Can Java edit the color in the XML drawable file? I just edited the background color and it dispersers the borders of the drawable.

String StatusColor=GetColor(Retailer_x.getStatus());
Stts.setBackgroundColor(Color.parseColor(StatusColor));

Solution

  • ShapeDrawable sd1 = new ShapeDrawable(new RectShape());
                            sd1.getPaint().setColor(CommonUtilities.color);
                            sd1.getPaint().setStyle(Style.STROKE);
                            sd1.getPaint().setStrokeWidth(CommonUtilities.stroke);
                            sd1.setPadding(15, 10, 15, 10);
    
                            sd1.getPaint().setPathEffect(
                                    new CornerPathEffect(CommonUtilities.corner));
                            ln_back.setBackgroundDrawable(sd1);