'Dynamic circular background for textview android

I use oval shape background for textview but the problem is,I have to set height and width of the textview in xml manually ,then only it will look like a circle, is there any way to make the circular background re-size itself according to the text length dynamically?

circle.xml

<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid
    android:color="@color/Color_500"/>
</shape>

layout.xml

<TextView
    android:layout_width="56dp" //is it possible to make it dynamic according to the text length?
    android:layout_height="56dp" 
    android:background="@drawable/circle"
    android:text="@string/longtext"/>


Solution 1:[1]

By using GradientDrawable we can get expected output. Actually we have to set the background to the TextView programmatically after rendering and after that create a background drawable with respect to the size of TextView.

Please use below code for more clarity.

val view = binding.notificationCountTv // TextView
    view.post {
        val size =
            view.width.coerceAtLeast(view.height)

        val bgDrawable = GradientDrawable()
        bgDrawable.shape = GradientDrawable.OVAL
        bgDrawable.setSize(size,size) // To make a circle

        view.background = bgDrawable

        view.text = "8"
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 NRUSINGHA MOHARANA