Search code examples
androidbuttonrounded-corners

Button with rounded corners and border with color


I need your help with something im trying to do, I've been trying to make a button with rounded corners and showing just the border of it, I need to be able to change the color programmatically depending on what I get from a web service, so far I tried to add the shape with a drawable and it gave the rounded shape with the border color, but I don't if is possible to change the color of it because its added by default in the drawable

<?xml version="1.0" encoding="UTF-8"?>

<stroke android:width="3dp"
    android:color="#ff000000"
    />

<padding android:left="1dp"
    android:top="1dp"
    android:right="1dp"
    android:bottom="1dp"
    />

<corners android:bottomRightRadius="7dp"
    android:bottomLeftRadius="7dp"
    android:topLeftRadius="7dp"
    android:topRightRadius="7dp"/>

that is the drawable I was using, then I tried to add the shape creating a custom class for the button and changing the onDraw method, and im getting a shape but is kinda weird

Rounded shape

@Override
protected void onDraw(Canvas canvas) {
    // TODO Auto-generated method stub

    Paint paint = new Paint();
    paint.setStyle(Paint.Style.STROKE);
    paint.setColor(strokeColor);
    paint.setStrokeWidth(5.0f);

    int  h = this.getHeight();
    int  w = this.getWidth();
    //final RectF rect = new RectF();

    RectF oval1 = new RectF(0, 0, w, h);
    canvas.drawRoundRect(oval1, 40, 40, paint);

}

and for some reason besides the weird shape im adding the text programmatically with set text method and its not showing, it gets the color for the stroke but not the text

buttonCTA = ButterKnife.findById(this, R.id.btnCTA);
        buttonCTA.setTextColor(Color.parseColor(valueColor));
        buttonCTA.setStrokeColor(valueColor);
        buttonCTA.setText("test");

Solution

  • This one is what you need.

        public static void setRoundedDrawable(Context context, View view, int backgroundColor, int borderColor) {
        GradientDrawable shape = new GradientDrawable();
        shape.setShape(GradientDrawable.RECTANGLE);
        shape.setCornerRadius(20f);
        shape.setColor(backgroundColor);
        if (borderColor != 0){
            shape.setStroke(2f, borderColor);
        }
        view.setBackgroundDrawable(shape);
    }
    

    You can change corner radius and stroke width depends on what you need. Hope it helps!