1

I want to add border from all sides to my RelativeLayout at runtime. I am able to get the border, however it is changing the background color of the layout. If I set the background color to white, it is also changing the border color to white. How do I avoid that?

Here is my code below:

private static void drawBorder(Context context, View layout){

    final RectShape rect = new RectShape();
    final ShapeDrawable rectShapeDrawable = new ShapeDrawable(rect);

    final Resources res = context.getResources();

    final Paint paint = rectShapeDrawable.getPaint();
    paint.setFlags(Paint.ANTI_ALIAS_FLAG);
    paint.setColor(Color.BLUE);
    paint.setStyle(Style.STROKE);
    paint.setStrokeWidth(10);

    layout.setBackgroundDrawable(rectShapeDrawable); //Testing on phone with API < 16

}

Thanks.

Onik
  • 19,396
  • 14
  • 68
  • 91
void
  • 187
  • 1
  • 3
  • 13

2 Answers2

0

Just make an xml file with the following border description

<shape xmlns:android="http://schemas.android.com/apk/res/android"
   android:shape="rectangle">
<corners
  android:radius="2dp"
  android:topRightRadius="0dp"
  android:bottomRightRadius="0dp"
  android:bottomLeftRadius="0dp" />
<stroke
  android:width="1dp"
  android:color="@android:color/white" />
</shape>

and set backgroundresource for the view with this drawable

elmorabea
  • 3,243
  • 1
  • 14
  • 20
  • Thanks for your response. I tried your method however, it is drawing the border, but changing the background color of the layout to Gray. The same as I was getting in the code above. – void Jul 03 '14 at 16:20
  • set the fill color to transparent – elmorabea Jul 04 '14 at 01:05
0

You can use this:

private static Bitmap drawBitmapWithBorders(int width, int height, int borderWidth,
                                     int backgroundColor, int borderColor){
    int pixels[] = new int[width*height];
    Arrays.fill(pixels, borderColor);
    for(int i=borderWidth;i<height-borderWidth;i++){
        Arrays.fill(pixels, i*width+borderWidth, (i+1)*width-borderWidth, backgroundColor);
    }
    return Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888);
}
Sander
  • 674
  • 1
  • 5
  • 17