Skip to content

Instantly share code, notes, and snippets.

@arriolac
Created July 14, 2022 22:44
Show Gist options
  • Save arriolac/0945dc79bc9df9db758d88d1d3a103ad to your computer and use it in GitHub Desktop.
Save arriolac/0945dc79bc9df9db758d88d1d3a103ad to your computer and use it in GitHub Desktop.
Using LazyListState to correctly remember state in an RV
// Copyright 2022 Google LLC.
// SPDX-License-Identifier: Apache-2.0
@Composable
fun ItemRow(index: Int, state: LazyListState) {
Column(Modifier.fillMaxWidth()) {
Text("Row #${index + 1}", Modifier.padding(horizontal = 8.dp))
LazyRow(state = state) {
// ...
}
}
}
class RecyclerViewAdapter : RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>() {
private val rowStates = mutableMapOf<Int, LazyListState>()
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val itemRow: ComposeItemRow = itemView.findViewById(R.id.itemRow)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val inflater = LayoutInflater.from(parent.context)
return ViewHolder(inflater.inflate(R.layout.interop_demo_row, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val state = rowStates.getOrPut(position) { LazyListState() }
holder.itemRow.index = position
holder.itemRow.rowState = state
}
override fun getItemCount(): Int = 50
}
class ComposeItemRow @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0
) : AbstractComposeView(context, attrs, defStyle) {
var index by mutableStateOf(0)
var rowState: LazyListState? by mutableStateOf(null)
@Composable
override fun Content() {
ItemRow(index, rowState!!)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment