如何在 android 中以编程方式设置 android:id?

how to set android:id in programmatically in android?

我想以编程方式设置 android:id = "@android:id/background"。 我尝试以编程方式将可绘制 xml 代码改编为 java 代码。 我将其他选项写入代码,但无法将 android:id = "@android:id/background" 写入代码。 这是我的代码。请告诉我路。

xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@android:id/background">
        <shape android:shape="rectangle">
            <corners android:radius="10dp"/>
            <solid android:color="@color/colorOrange"/>
            <stroke android:color="#fff" android:width="1dp"/>
        </shape>
    </item>
    <item android:id="@android:id/progress">
        <scale
            android:scaleHeight="10%"
            android:scaleWidth="100%" >
            <shape android:shape="rectangle">
                <corners android:radius="10dp"/>
                <solid android:color="@color/colorGreen"/>
                <stroke android:color="@color/colorGreen"
                    android:width="4dp"/>
            </shape>
        </scale>
    </item>
</layer-list>

代码

        val layer1 = GradientDrawable()
        layer1.cornerRadius = 10f
        layer1.setStroke(1, Color.WHITE)
        layer1.setColor(Color.YELLOW)

        val scaleDrawable =  GradientDrawable()
        scaleDrawable.cornerRadius = 10f
        scaleDrawable.setStroke(1, Color.WHITE)
        scaleDrawable.setColor(Color.BLUE)
        val layer2 = ScaleDrawable(scaleDrawable, Gravity.BOTTOM,1f,0.1f)
        val drawableList = arrayOf(layer1, layer2)
        val layerList : LayerDrawable = LayerDrawable(drawableList)
        this.progressDrawable = layerList

结果屏幕

您可以使用 #layerList.setId 并通过索引设置 ID。检查下面的代码。我对它做了一些改动以使其与 xml-drawable 相匹配。

val layer1 = GradientDrawable()
layer1.cornerRadius = 10f
layer1.setStroke(1, Color.WHITE)
layer1.setColor(Color.YELLOW)

val scaleDrawable =  GradientDrawable()
scaleDrawable.cornerRadius = 10f
scaleDrawable.setStroke(1, Color.WHITE)
scaleDrawable.setColor(Color.BLUE)

val layer2 = ScaleDrawable(scaleDrawable, Gravity.START,1f,0.1f)
val drawableList = arrayOf(layer1, layer2)
val layerList  = LayerDrawable(drawableList)
layerList.setId(0,android.R.id.background)
layerList.setId(1,android.R.id.progress)
seekBar.progressDrawable = layerList