简体   繁体   English

Jetpack Compose:如何将列表项包装在卡片中

[英]Jetpack Compose: How to wrap list items inside a Card

I have a screen where I need to show a header and a list of items wrapped in a card view.我有一个屏幕,我需要在其中显示一个标题和一个包裹在卡片视图中的项目列表。 The whole screen has to be scrollable (like shown in the image below).整个屏幕必须是可滚动的(如下图所示)。

在此处输入图片说明

I know how to do this with a scrollable Column but I want to be able to use a LazyColumn (because each list item will have its own ViewModel due to the complexity of the view and I thought LazyColumn will be more resources-efficient).我知道如何使用可滚动的列来做到这一点,但我希望能够使用LazyColumn (因为由于视图的复杂性,每个列表项都有自己的 ViewModel,我认为 LazyColumn 会更节省资源)。 For the header, I can use item and for the list, I can use items .对于标题,我可以使用item ,对于列表,我可以使用items Below is the code I tried:下面是我试过的代码:

@Composable
fun Screen(
  items: List<String>
) {
  Column(
    Modifier.fillMaxSize()
  ) {
    TopAppBar(title = { Text(text = "My Activity") })

    LazyColumn {

      // Header
      item {
        Text("Title", Modifier.padding(32.dp))
      }

      // I cannot use Box in this way here
      Box(Modifier.padding(32.dp)) {
        Card {
          items(items.size) {
            Text("Item $it")
          }
        }
      }
    }
  }
}

The problem with that code is that I cannot wrap the list items in a card view because Card is not a LazyListScope .该代码的问题在于我无法将列表项包装在卡片视图中,因为Card不是LazyListScope Using LazyColumn, how can I wrap the list items in a Card?使用 LazyColumn,如何将列表项包装在卡片中?

You can define your "Card" as a single item containing nested items .你可以定义你的“卡”作为一个单一的item包含嵌套的items

items being part of LazyListScope you need to use kotlin explicit this such as this@LazyColumn itemsLazyListScope一部分,您需要使用 kotlin 明确this例如this@LazyColumn

@Composable
fun Screen(
    items: List<String>
)  {
    Column(
        Modifier.fillMaxSize()
    ) {
        TopAppBar(title = { Text(text = "My Activity") })
        LazyColumn( Modifier.fillMaxSize()) {

            // Header
            item {
                Text("Title", Modifier.padding(32.dp))
            }

            // Single item
            item {
                // Your Box list here
                Box(Modifier.padding(32.dp)) {
                    Card {
                        this@LazyColumn.items(items.size) {
                            Text("Item $it")
                        }
                    }
                }
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM