Home » Android » android – How do I set the rounded corner radius of a color drawable using xml?

android – How do I set the rounded corner radius of a color drawable using xml?

Posted by: admin March 11, 2020 Leave a comment


On the android website, there is a section about color drawables. Defining these drawables in xml looks like this:

    <drawable name="solid_red">#f00</drawable>
    <drawable name="solid_blue">#0000ff</drawable>
    <drawable name="solid_green">#f0f0</drawable>

In the java api, they have thr following method to define rounded corners:

setCornerRadius(float radius)

Is there a way to set the rounded corners in the xml?

How to&Answers:

Use the <shape> tag to create a drawable in XML with rounded corners. (You can do other stuff with the shape tag like define a color gradient as well).

Here’s a copy of a XML file I’m using in one of my apps to create a drawable with a white background, black border and rounded corners:

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <solid android:color="#ffffffff"/>    

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

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

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


mbaird’s answer works fine. Just be aware that there seems to be a bug in Android (2.1 at least), that if you set any individual corner’s radius to 0, it forces all the corners to 0 (at least that’s the case with “dp” units; I didn’t try it with any other units).

I needed a shape where the top corners were rounded and the bottom corners were square. I got achieved this by setting the corners I wanted to be square to a value slightly larger than 0: 0.1dp. This still renders as square corners, but it doesn’t force the other corners to be 0 radius.


Try below code

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    android:topRightRadius="30dp" />
<solid android:color="#1271BB" />

    android:color="#1271BB" />

    android:top="1dp" /></shape>