0

There are so pretty good solutions for creating a round Button. (How to make a round button?)

Most of these however seem to hard-code the color in the button xml file.

Is there a way to create a round button with a configurable/styleable color? (I don't like the idea of creating one xml file for each color button I might use)

Ideally I would apply the color when i use my RoundButton, in my layout.xml, like for a View.

Note: My Button needs to contain text, so it can also be a TextView.

Thanks

Community
  • 1
  • 1
user1654757
  • 300
  • 1
  • 5
  • 14

3 Answers3

3

Define xml without color (xml from your link):

roundedbutton.xml:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:bottomRightRadius="8dip"
    android:bottomLeftRadius="8dip"
    android:topRightRadius="8dip"
    android:topLeftRadius="8dip"/>

button.xml:

<Button
   android:layout_height="50dp"
    android:layout_width="90dp"
    android:id="@+id/button"
    android:text="Button"
    android:background="@drawable/roundedbutton"/>

And you can do it like this:

 button.getBackground().setColorFilter(Color.parseColor("#bbe618"), PorterDuff.Mode.SRC_IN);

Result:

enter image description here

Djordje Tankosic
  • 1,975
  • 2
  • 20
  • 21
0

If you want a simple button with round corners you can use directly the CardView from here: round corners. You can set programatically the CardView background color and keeps the ripple with its foreground=?selectableitembackground

For circle button you can use this library: circle button

JavierSegoviaCordoba
  • 6,531
  • 9
  • 37
  • 51
0

You can make a function like this and pass a view and color to it.

/**
 * 
 * @param v: Can be any view like Button, Textview, Linearlayout,etc
 * @param color: Background color which you want
 */
public static void setRoundedBackGround(View v, int color)
{
    GradientDrawable drawable = new GradientDrawable();
    drawable.setShape(GradientDrawable.RING);
    drawable.setStroke(3, Color.BLACK); // You can set any border color 

    if(color == 0)
    {
        drawable.setColor(Color.TRANSPARENT);
        v.setBackgroundDrawable(drawable);
    }
    else
    {
        drawable.setColor(color);
        v.setBackgroundDrawable(drawable);
    }
}

Hope this might help you.

rahul shah
  • 2,086
  • 2
  • 11
  • 14