How to create recycler view in Compose Jetpack?
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")
}
}
- LazyColumnFor for a vertical list
- LazyRowFor for a horizontal list
Hope it's helpful for you.
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.
Update March 2021: Starting from 1.0.0-beta01
LazyColumn
for a vertical listLazyRow
for a horizontal list
For example:
@Composable
fun LazyRowItemsDemo() {
LazyRow {
items((1..1000).toList()) {
Text(text = "Item $it")
}
}
}