Change shape border color at runtime

Zelter Ady picture Zelter Ady · Nov 27, 2012 · Viewed 12.9k times · Source

I have this shape in my drawable folder:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="5dp" />
    <solid android:color="#ffffff" />
    <stroke android:width="2dp" android:color="#B5B5B5"/>
</shape>

This define a rectangle with rounded corners and I can apply it as background to any panel like this: android:background="@drawable/round_corner_shape".

Here comes the question: I have few panels on my application, with the same shape as background, but for each shape I want a different border (stroke) color. I don't want to create 3 shapes, the only difference to be on the stroke color. Is it possible to change at runtime the stroke value?

Answer

rodalves picture rodalves · Feb 23, 2013

I had the same problem. In my case, I had a GridView, which the items in grid could have the border color changed by the user at runtime.

So, in the gridviewAdapter for that grid, I did the following in the getView method (the one that generates the view for the adapter)

public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    convertView = inflater.inflate(R.layout.griditem, null);
    GradientDrawable gradientDrawable = (GradientDrawable) convertView.getBackground(); 

    gradientDrawable.setStroke(2, mColor); 
    convertView.invalidate();
    return convertView;
}

mColor is a int that represents the color, much like we do in the xml files. In java code, instead of "#" we use "0x" to define it in the AARRGGBB format. For example, use 0xFF000000 for 100% opaque BLACK and 0xFF0000FF for 100% opaque BLUE. Explaining this here since the google api 'helpfully' tells that the int color is "the color of the stroke".

This solved my problem... I guess you can try something similar for your case.