如何通过程序动态创建具有两种颜色的条纹Drawable?

3
类似于10年前提出的这个问题: 有两种颜色的带状背景? 我需要创建一个可用作通用视图背景的可绘制对象,它具有两种不同的矩形条纹颜色,就像一面旗帜。如果其中一个矩形拥有弯曲的角落,那就更好了。不幸的是,我需要动态设置颜色,所以无法在xml中定义这个可绘制对象。我该如何在Kotlin中实现这个目标?
我最好的猜测是这样的,但它不起作用:
background = LayerDrawable(
    arrayOf(
        GradientDrawable().apply {
            shape = GradientDrawable.RECTANGLE
            layout(0, 0, 100, 20)
            background = styles.rootBackground
        },
        GradientDrawable().apply {
            shape = GradientDrawable.RECTANGLE
            cornerRadii = floatArrayOf(8f, 8f, 8f, 8f, 0f, 0f, 0f, 0f)
            layout(0, 20, 100, 40)
            color = styles.robotTextBackgroundColor //requires color state list ?!
        }
    )
)
1个回答

2
很遗憾,我需要动态设置颜色,所以无法在xml中定义这个可绘制对象。
不,你可以将其作为XML可绘制对象,然后在代码中进行填充,并更改颜色。这比从头开始编写代码要容易得多。
但是这需要给需要更改颜色的图层列表项附加ID。
这是来自参考帖子的演示。

R.drawable.test:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/redRect"
        android:bottom="20dp">
        <shape android:shape="rectangle">
            <size android:height="20dp" />
            <solid android:color="#ff0000" />
        </shape>
    </item>

    <item
        android:id="@+id/blueRect"
        android:top="20dp">
        <shape android:shape="rectangle">
            <size android:height="20dp" />
            <solid android:color="#0000ff" />
        </shape>
    </item>

</layer-list>

在这里,我们将把redRect项目的颜色从红色改为绿色,然后将整个可绘制对象设置为根视图的背景。
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val background = ResourcesCompat.getDrawable(resources, R.drawable.test, null)
    if (background is LayerDrawable) {
        val bgLayer =
            background.findDrawableByLayerId(R.id.redRect) as GradientDrawable

        bgLayer.setColor(Color.GREEN)

        findViewById<ConstraintLayout>(R.id.root).background = background
    }
}

enter image description here

如果我能让其中一个矩形有圆角,那就更好了。
你可以在形状内使用标签,并定义半径:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/redRect"
        android:bottom="20dp">
        <shape android:shape="rectangle">
            <size android:height="20dp" />
            <solid android:color="#ff0000" />
            <corners android:radius="30dp" />
        </shape>
    </item>

    <item
        android:id="@+id/blueRect"
        android:top="20dp">
        <shape android:shape="rectangle">
            <size android:height="20dp" />
            <solid android:color="#0000ff" />
            <corners
                android:bottomLeftRadius="30dp"
                android:bottomRightRadius="30dp" />
        </shape>
    </item>

</layer-list>

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接