Rounded Corners + background Color Dynamic setting for Android button?

Ganesh K picture Ganesh K · Sep 25, 2014 · Viewed 9.2k times · Source

I would like to give below settings for Button in my application. You can think it as some theme changing for buttons.

Style Rounded or Normal

Color Red or yellow or blue or any Color code

I know with Shape defined in XML, I can achieve Rounded Corners. With setBackgroundColor, I can set any Color as background.

problem

Both setBackgroundColor, setBackground are overriding one another based on the order i call them. So I can't achieve both effects on the same button. How can I achieve these two effects simultaneously. How can I get below multiple buttons from single Button class. Thanks in Advance.

enter image description here

Answer

Andrey Danilov picture Andrey Danilov · Oct 26, 2017

Well I did it with GradientDrawable

    int color = Color.rgb(255,0,0); //red for example
    int radius = 5; //radius will be 5px
    int strokeWidth = 2;

    GradientDrawable gradientDrawable = new GradientDrawable();
    gradientDrawable.setColor(color);
    gradientDrawable.setCornerRadius(radius);
    gradientDrawable.setStroke(strokeWidth, color);
    button.setBackground(gradientDrawable);