Change shape border color at runtime
Asked Answered
C

2

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?

Crenellate answered 27/11, 2012 at 13:39 Comment(1)
thats something to think about, good question. +1Furgeson
C
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.

Costotomy answered 23/2, 2013 at 18:34 Comment(0)
D
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);
Daubigny answered 27/11, 2012 at 13:50 Comment(3)
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.Crenellate
worked for me. but for copy&paste purpose it should be bg.getPaint().setColor(0x99FFFFFF);Capitalistic
colors the background , not stroke.Vilmavim

© 2022 - 2024 — McMap. All rights reserved.