How to assign button rounding and random colors at the same time?

2

I'm not sure what to do.

For example I have a button on this button I play random colors on it, I have a List List Colors = new ArrayList (); and in that list I save the colors in Hexadecimal, until then without problems I use Collections.shuffle () and get a random color from the list and on the button I use bt1.setBackgroundColor (), my biggest doubt is I'm wanting my buttons of my application stay with the rounded corners, I know I have to use something like this

cantosredondodos.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#33DDFF" />
    <corners android:radius="4dp" />
</shape>

But if I put this xml as background there in the button's xml

<Button
    android:text="Button"
    android:textAllCaps="false"
    android:layout_width="110dp"
    android:layout_height="wrap_content"
    android:id="@+id/button1"
    android:background="@drawable/cantosredondodos"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

The backgroud I set before in the code will overwrite the part of the xml I want to make the radius, would it have any solution? to do everything in the application code ?, I even thought of doing several xmls but I believe it would not be very cool, as I have more than 10 buttons would not be a very viable thing ...

    
asked by anonymous 01.02.2017 / 12:58

1 answer

3

You can set the border programmatically using shape.setStroke(3, borderColor) , where 3 represents the border and borderColor represents the border color using GradientDrawable . See this function below, which I pass as a parameter to view , which would be its button, backgroundColor and borderColor . See:

public static void customView(View v, int backgroundColor, int borderColor){
    GradientDrawable shape = new GradientDrawable();
    shape.setShape(GradientDrawable.RECTANGLE);
    shape.setCornerRadii(new float[] { 8, 8, 8, 8, 0, 0, 0, 0 });
    shape.setColor(backgroundColor);
    shape.setStroke(3, borderColor);
    v.setBackgroundDrawable(shape);
}

You can customize according to your ideas.

To set a color randomly you can use the class Random . See:

Random rnd = new Random(); 
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));  
    
01.02.2017 / 13:14