undermark5
03/21/2023, 9:02 PM@Composable
fun MySectionedLazyList(viewModel: SectionedListViewModel) {
LazyColumn(modifier = Modifier.fillMaxSize()) {
viewModel.section1?.let {
items(items = it.items, key ={it.key}) {
Item1(it.data)
}
}
viewModel.section2?.let {
items(items = it.items, key ={it.key}) {
Item2(it.data)
}
}
viewModel.section3?.let {
items(items = it.items, key ={it.key}) {
Item3(it.data)
}
}
}
}
and I would like to scroll to the 5th item in section3
, but I don’t know it’s index, only it’s key, how would I accomplish such a task? Everything I’m seeing requires use of the item index, which while I could compute, it would be much easier if there was a way to scroll to an item with a specific key rather than just based off index.
Is this just functionality that I’d have to implement myself?undermark5
03/21/2023, 9:08 PMephemient
03/21/2023, 9:08 PMundermark5
03/21/2023, 9:10 PMephemient
03/21/2023, 9:10 PMephemient
03/21/2023, 9:10 PMLazyListScope
with your own that tracks the keys/indicesundermark5
03/21/2023, 9:13 PMephemient
03/21/2023, 9:27 PMfun LazyListScope.logKeys(content: LazyListScope.() -> Unit): List<Any> = buildList {
object : LazyListScope by this@logKeys {
override fun item(key: Any?, contentType: Any?, content: @Composable (LazyItemScope.() -> Unit)) {
this@buildList.add(key ?: this@buildList.size)
this@logKeys.item(key, contentType, content)
}
override fun items(
count: Int,
key: ((index: Int) -> Any)?,
contentType: (index: Int) -> Any?,
itemContent: @Composable (LazyItemScope.(index: Int) -> Unit)
) {
this@buildList.addAll(List(count) { key?.invoke(it) ?: (this@buildList.size + it) })
this@logKeys.items(count, key, contentType, itemContent)
}
}.content()
}
var keys by remember { mutableStateOf(emptyList<Any>()) }
val state = rememberLazyListState()
LazyColumn(state = state) {
keys = logKeys {
items(...)
}
}
state.scrollToItem(keys.indexOf(key))
dewildte
03/21/2023, 11:01 PMis the real answer to combine everything to be displayed into a single list instead?I suggest doing this. I did this on a project I am working on and it’s reliable.
dewildte
03/21/2023, 11:03 PMdewildte
03/21/2023, 11:03 PMdewildte
03/21/2023, 11:04 PMdewildte
03/21/2023, 11:05 PMundermark5
03/22/2023, 3:28 PMwhen
block that is in charge of dispatching to the correct composable for each item in the list? I’d prefer to keep the logic out of the view, but I’d also like to keep the view out of the data class, and I think both of those things are at odds with each other. Which comes back to my previous comment about wishing Kotlin supported multiple dispatch as then the logic is handled by the language rules.