2

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"/>
Aditi Parikh
  • 1,522
  • 3
  • 13
  • 34
Sai
  • 15,188
  • 20
  • 81
  • 121

1 Answers1

0

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"
    }
NRUSINGHA MOHARANA
  • 1,489
  • 8
  • 13