jetpack compose 中的图层列表相当于什么?

BeG*_*eGo 2 android kotlin android-jetpack-compose

jetpack compose 中的图层列表相当于什么?

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/lightGray" />
    <item android:drawable="@drawable/transp_01" />
</layer-list>
Run Code Online (Sandbox Code Playgroud)

我想要获得一张如图所示的图像作为我所有屏幕的背景

在此输入图像描述

Phi*_*hov 5

您可以轻松地在 compose 中绘制它。您可以Box将任意数量的图像放置在彼此的顶部,就像图层列表一样。所以一般来说,你可以使用这样的东西:

Box {
    // replace any color item from the layer list with box with background:
    Box(
        modifier = Modifier
            .background(Color.LightGray)
            .matchParentSize()
    )
    // replace drawable item with Image:
    Image(
        painter = painterResource(id = R.drawable.my_image),
        contentDescription = "...",
    )
}
Run Code Online (Sandbox Code Playgroud)

但就您而言,看起来您只需要一张图像,并且可以为其设置背景颜色。由于您需要在应用程序中重用它,因此可以将其移动到单独的视图,例如如下所示:

@Composable
fun BackgroundView(modifier: Modifier) {
    Image(
        painter = painterResource(id = R.drawable.transp_01),
        contentDescription = "...",
        modifier = modifier.background(Color.LightGray)
    )
}
Run Code Online (Sandbox Code Playgroud)

然后将其设置为任何屏幕的背景,如下所示:

@Composable
fun SomeScreen() {
    Box(Modifier.fillMaxSize()) {
        BackgroundView(Modifier.matchParentSize())
        // screen content
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这在视觉结果方面是等效的,但在绕过资源系统的意义上却不同。 (3认同)