How to create recycler view in Compose Jetpack?
D

7

17

Is there any special way to create recyclerView in Compose Jetpack? Or it is the same as usual?

Dilemma answered 4/11, 2019 at 10:41 Comment(1)
M
13

Update March 2021: Starting from 1.0.0-beta01

For example:

@Composable
fun LazyRowItemsDemo() {
    LazyRow {
        items((1..1000).toList()) {
            Text(text = "Item $it")
        }
    }
}
Metagalaxy answered 1/9, 2020 at 8:23 Comment(2)
Is there a way to reverse the LazyColumnFor like you can with ScrollableColumn( reverseScrollDirection = true)?Scherman
full source code is available with an example github.com/sureshmaidaragi1919/ComposeLazyColumnChristianity
F
10

Examples from JetNews app have static data. It's worth to mention that according to the recent Google presentation (see especially from 18:30), we should consider ScrollingList, which is intended for list with undefined number of elements (e.g. downloaded from the web), what was traditionally handled by RecyclerView. Then, it should look like this:

@Composable
fun NewsFeed(stories: List<StoryData>) {
  ScrollingList(stories) { story ->
    StoryWidget(story)
  }
}

or we can do similar thing with LiveData or RxJava Observable/Flowable:

@Composable
fun NewsFeed(stories: LiveData<List<StoryData>>) {
  ScrollingList(stories.observe()) { story ->
    StoryWidget(story)
  }
}

In such case, we are re-using StoryWidget (or any other widget of our choice) in the every step of the iteration with data emitted dynamically through the lambda expression.

Fixer answered 9/11, 2019 at 18:9 Comment(2)
From where is ScrollingList element? I'm trying use it and it can not be found for the IDE.Nicko
@LucasSousa You are right. ScrollingList is not element. I google it and found that ScrollingList is not available now. It will be available in the next release. So, we have to wait. (Found here)Laris
C
7

In jetnews sample project for list/recyclerview they are using VerticalScroller with Column and using forEach to populate items below @Composable function is example

@Composable
private fun TabWithTopics(tabname: String, topics: List<String>) {
    VerticalScroller {
        Column {
            HeightSpacer(16.dp)
            topics.forEach { topic ->
                TopicItem(
                    getTopicKey(
                        tabname,
                        "- ",
                        topic
                    ), topic
                )
                TopicDivider()
            }
        }
    }
} 

For class and method check this link

https://github.com/android/compose-samples/blob/master/JetNews/app/src/main/java/com/example/jetnews/ui/interests/InterestsScreen.kt

For more information you can download/clone jetnews sample from check here's link

https://github.com/android/compose-samples/tree/master/JetNews

For latest Jetpack alpha release update the below:

@Composable
fun LazyRowItemsDemo() {
    LazyRowFor(items = (1..1000).toList()) {
        Text(text = "Item $it")
    }
}
  1. LazyColumnFor for a vertical list
  2. LazyRowFor for a horizontal list

Hope it's helpful for you.

Congest answered 4/11, 2019 at 11:37 Comment(1)
Yup. What about the recycling.Heartwarming
S
4

Even further update for the new comers. As of 0.1.0-dev14, AdapterList is deprecated in favor of LazyColumnItems and LazyRowItems.

Sweetener answered 11/7, 2020 at 9:38 Comment(0)
A
2

UPDATED and current implementation at dev06 Jetpack Compose uses AdapterList and you could use the simple example included by Nurseyit Tursunkulov and I can share a more complex (real case scenario use):

  • Your List<Any> must be "compose aware" and the current one available for that is ModelList<Any>
  • You can create a model using @Model tag as those change the state, and your @Compososable function will be aware (using a MutableList)

Example Code:

fun addLogic(modelList: ModelList<MyModel>) {
  modelList.add(MyModel("Smith John", 10))
}

class MyModel(var name: String, var index: Int)

@Composable
fun RecycledList() { // Any name you want
  val modelList<MyModel> = modelListOf()
  var counter = 0

  addLogic(modelList)

  modelList.add(MyModel("John Doe", 99))

  MaterialTheme {
    Column {
      Container(height = 70.dp) {
         Align(alignment = Alignment.Center) {
            Button(onClick = { 
               modelList.add(MyModel("John Smith", counter++))
               // Any other logic you want
            }) {
               Text("ADD ITEM")
            }
         }
      }
      AdapterList(data = modelList) { item ->
         Center {
            Text("Hello ${item.name} - Index: ${item.index}")
         }
      },
    }
  }
}

Result:

                                            AdapterList

Amourpropre answered 11/3, 2020 at 15:54 Comment(0)
D
0

According to this article there is new version:

@Composable
fun <T> AdapterList(
 data: List<T>,
 modifier: Modifier = Modifier.None,
  itemCallback: @Composable() (T) -> Unit
)

@Composable
 fun Scrollable(
dragDirection: DragDirection,
scrollableState: ScrollableState,
onScrollStarted: (startedPosition: PxPosition) -> Unit = {},
onScrollStopped: (velocity: Float) -> Unit = {},
enabled: Boolean = true,
children: @Composable() () -> Unit
)

 AdapterList(
    data = (1..20).map { it }.toList()
) {
    if (it % 2 == 0) {
        Text("$it Even", style = TextStyle(fontSize = 40.sp, color = 
  Color.Gray))
    } else {
        Text(text = "$it Odd", style = TextStyle(fontSize = 70.sp))
    }
}
Dilemma answered 9/3, 2020 at 5:28 Comment(0)
B
0

This is a sample code that uses AdapterList for implementing recylcerview in compose

@Composable
fun Feeds(feeds:LiveData<List<Feed>>) {
    val mFeeds by feeds.observeAsState(emptyList())
    AdapterList(data = feeds){feed->
    FeedsItem(feed)
    }
}
Bartram answered 13/6, 2020 at 14:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.