What is the Jetpack Compose equivalent of RecyclerView or ListView?

微笑、不失礼 提交于 2020-07-09 14:33:09

问题


In Jetpack Compose, how can I display a large list of data while laying out only the visible items, instead of composing and laying out every item on the initial layout pass? This would be similar to RecyclerView and ListView in the View toolkit.

One could use a for loop to place all of the components inside of a Column in a VerticalScroller, but this would result in dropped frames and poor performance on larger numbers of items.


Note: this is intended as a canonical self-answered question to pre-empt/handle similar questions


回答1:


Update: In an upcoming release (dev14), this has been renamed to LazyColumnItems for a vertical list, and LazyRowItems for a horizontal list. The API is otherwise the same.

The equivalent component to RecyclerView or ListView in the Jetpack Compose dev preview is AdapterList, which composes and lays out only the currently visible items.

You use it by formatting your data as a list and passing it with a @Composable callback that emits the UI for a given item in the list. For example:

val myData = listOf("Hello,", "world!")
LazyColumnItems(myData) { item ->
    Text(text = item)
}



回答2:


You can get the same essence of RecyclerView or ListView in JetpackCompose using AdapterList that's renamed in dev.14 preview version.

  • [LazyColumnItems] for vertically scrolling list
  • [LazyRowItems] for horizontally scrolling list

Check what's documentation says:

It was also moved into a lazy sub-package and split into two files. Plus I renamed params:

  1. data -> items. this seems to be more meaningful then just raw data
  2. itemCallback -> itemContent. this is more meaningful and we generally don't use word callback in the lambda names, especially for composable lambdas

Check how to use it:

@Composable
fun <T> LazyColumnItems(
  items: List<T>,
  modifier: Modifier = Modifier,
  itemContent: @Composable (T) -> Unit
) {
    LazyItems(items, modifier, itemContent, isVertical = true)
}

In .KT

LazyColumnItems(items = (0..50).toList()) { item ->
    cardViewImplementer(item)
 }

From my perspective LazyColumnItem or LazyRowItem is not working properly if your item layout is complex because it's stuck the list as a comparison to VerticalScroller working fine in this scenario.



来源:https://stackoverflow.com/questions/60765370/what-is-the-jetpack-compose-equivalent-of-recyclerview-or-listview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!