简体   繁体   中英

Android: creating circle button with background color programmatically

I am inflating dynamic buttons into TableRow with random colors. I would like to set the buttons to be in circle programmatically instead of rectangles.

Code:

bt[i][j].setBackgroundColor(Color.rgb(color_normal[0], color_normal[1], color_normal[2]));

Question:

Since the buttons are inflated dynamically with random colors, the button layout cannot be set through xml. How could a button be created with random colors and in circle shape programmtically? (Rather than placing a imageview with transparent center on top of the button)?

Thanks!

Create a file oval.xml in the drawable folder that looks something like:

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

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >

    <gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF"
        android:angle="270"/>

</shape>

Now set button as

<Button
    android:id="@+id/button1"

    android:layout_width="100dp"

    android:layout_height="100dp"

    android:background="@drawable/oval_shape"

    android:text="Button" />

in your layout file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM