【问题标题】:Dynamic circular background for textview androidtextview android的动态圆形背景
【发布时间】:2022-04-07 10:27:06
【问题描述】:

我为 textview 使用椭圆形背景,但问题是,我必须在 xml 中手动设置 textview 的高度和宽度,然后它才会看起来像一个圆圈,有没有办法让圆形背景重新调整大小自己根据文本长度动态吗?

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"/>

【问题讨论】:

  • 当然:创建您的自定义 android.graphics.drawable.Drawable 类并使用您喜欢的任何内容覆盖其 draw 方法
  • 嗨赛,你有解决这个问题的办法吗?任何帮助将不胜感激。

标签: android android-layout


【解决方案1】:

通过使用GradientDrawable,我们可以获得预期的输出。实际上,我们必须在渲染后以编程方式将背景设置为TextView,然后根据TextView 的大小创建背景drawable

为了更清楚,请使用下面的代码。

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"
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-28
    • 2011-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多