Creating a Circle Shape in Android XML Drawable

Creating a Circle Shape in Android XML Drawable

6 June 2024 Stephan Petzl Leave a comment Tech-Help

Defining shapes in XML for Android can sometimes be challenging, especially when documentation is sparse. If you’re looking to create a simple circle filled with a solid color in an XML file for use in your layout files, you’re in the right place. This guide will walk you through the process step-by-step.

Basic Circle Shape

To define a basic circle shape in an Android XML drawable file, you can use the following XML code:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="#666666"/>
    <size android:width="120dp" android:height="120dp"/>
</shape>

This XML code creates a circle with a solid color of #666666 and a size of 120dp by 120dp.

Adding a Stroke

If you want to add a stroke to your circle, you can modify the XML as follows:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="#48b3ff"/>
    <stroke android:width="2dp" android:color="#444444"/>
</shape>

This code adds a 2dp stroke with the color #444444 to the circle.

Using VectorDrawable

For more complex shapes or better scalability, you can use a VectorDrawable:

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="200dp"
    android:height="200dp"
    android:viewportHeight="64"
    android:viewportWidth="64">
    <path android:fillColor="#ff00ff"
        android:pathData="M22,32 A10,10 0 1,1 42,32 A10,10 0 1,1 22,32 Z"/>
</vector>

This VectorDrawable creates a scalable circle with a fill color of #ff00ff.

Practical Example

To use these shapes in your layout, you can set them as the background of a view:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/circle_shape"
/>

This example sets the background of a Button to the circle shape defined in the circle_shape.xml file.

Conclusion

Creating circle shapes in Android XML drawable files is straightforward once you understand the basic structure. Whether you’re using a simple shape, adding strokes, or leveraging vector drawables, these methods provide flexibility and scalability for your UI designs.

Enhance Your Testing with Repeato

If you’re a mobile developer looking to streamline your testing process, consider using Repeato. Repeato is a no-code test automation tool for iOS and Android that allows you to create, run, and maintain automated tests quickly and efficiently. With Repeato, you can focus on creating a great product while ensuring robust testing. Plus, it enables non-technical colleagues to participate in the testing process, making it a versatile tool for any development team.

Like this article? there’s more where that came from!