【问题标题】:How to add dividers between items in a LazyColumn Jetpack Compose?如何在 LazyColumn Jetpack Compose 中的项目之间添加分隔符?
【发布时间】:2021-07-12 08:20:25
【问题描述】:

我有一个像这样的 LazyColumn:

LazyColumn (
    verticalArrangement = Arrangement.spacedBy(12.dp)
) {
    items(bookList) { book ->
        InProgressBookItem(book = book)
    }
}

如何在列表中的每个项目之间添加一条线,类似于在旧的 RecyclerView 上使用项目装饰?

【问题讨论】:

    标签: android android-jetpack-compose android-jetpack-compose-list


    【解决方案1】:

    目前,1.0.x 没有内置方法来添加分隔符。但是,您可以在LazyListScope 中添加Divider

    类似:

    LazyColumn(
        verticalArrangement = Arrangement.spacedBy(12.dp),
    ) {
        items(itemsList){
            Text("Item at  $it")
            Divider(color = Color.Black)
        }
    }
    

    如果您不希望最后一个项目后跟 Divider,您可以根据项目的索引为项目添加分隔符:

    LazyColumn(
        verticalArrangement = Arrangement.spacedBy(12.dp),
    ) {
        itemsIndexed(itemsList) { index, item ->
    
            Text("Item at index $index is $item")
    
            if (index < itemsList.lastIndex)
                Divider(color = Color.Black, thickness = 1.dp)
        }
    }
    

    【讨论】:

    • 这是我的第一个想法,但我希望有一种更优雅/内置的方式来做到这一点。现在,这应该可以了,谢谢!
    • 提示:你可以写index &lt; itemsList.lastIndex而不是index &lt; itemsList.size-1
    【解决方案2】:

    简单:

    LazyColumn (
        verticalArrangement = Arrangement.spacedBy(12.dp)
    ) {
        items(bookList) { book ->
            InProgressBookItem(book = book)
            Divider(color = Color.Black, thickness = 1.dp)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-30
      • 2022-11-24
      • 1970-01-01
      • 1970-01-01
      • 2022-10-04
      • 1970-01-01
      • 1970-01-01
      • 2021-12-12
      相关资源
      最近更新 更多