30

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?

Zelter Ady
  • 6,266
  • 12
  • 48
  • 75

2 Answers2

20

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.

chtenb
  • 14,924
  • 14
  • 78
  • 116
rodalves
  • 201
  • 2
  • 3
1

Hi you can try create your background on runtime, then you can change it whenever you want.

RoundRectShape rect = new RoundRectShape(
  new float[] {30,30, 30,30, 30,30, 30,30},
  null,
  null);
ShapeDrawable bg = new ShapeDrawable(rect);
bg.getPaint().setColor(0x99FFFFFF);
view.setBackgroundDrawable(bg);
dsh
  • 12,037
  • 3
  • 33
  • 51
Talha
  • 12,673
  • 5
  • 49
  • 68
  • 1
    But in your example I don't use the my existing xml code. I want to define a shape (corner radius, background, stoke width) in xml (or other way, but with all the parameters above) and to change only the stroke color if I need. This was the question, if you can help. – Zelter Ady Nov 27 '12 at 13:54
  • 1
    worked for me. but for copy&paste purpose it should be `bg.getPaint().setColor(0x99FFFFFF);` – bass.t May 28 '13 at 13:50
  • 3
    colors the background , not stroke. – lalitm Sep 06 '14 at 04:58