https://kotlinlang.org logo
#compose
Title
# compose
m

Miguel Vargas

12/14/2021, 12:00 AM
AndroidViews inside a LazyColumn recompose and recreates the Views as I scroll. I tried using
remember
to save the AndroidView as follows but it’s still recreating the Views as I scroll up and down. Is there any way to make it more efficient?
Copy code
@Composable
fun ViewInLazyColumn() {
    LazyColumn {
        items(100) { idx ->
            val context = LocalContext.current

            val view = remember { MyView(context, idx.toString()) }
            AndroidView(factory = { view }) } } }

class MyView(context: Context, value: String) : TextView(context) {
    init {
        // View keeps getting recreated
        println("init MyView $value") 
        text = value } }
a

Andrey Kulikov

12/14/2021, 12:42 AM
I guess what you mean is that there is a new View created every time there is a new item became visible. yes, it is expected, we do not really reuse the items as it was done in RecyclerView, especially the ones which are implemented as Views
m

Miguel Vargas

12/14/2021, 12:44 AM
But why even when I scroll back to a row I already saw. Why doesn’t the
remember
save the View
a

Andrey Kulikov

12/14/2021, 12:46 AM
only currently visible items are kept composed, the rest are disposed. when disposed everything remembered is lost
m

Miguel Vargas

12/14/2021, 12:47 AM
Oh! That’s good to know.
Now I’m thinking of trying to save the Views outside LazyColumn’s scope
3 Views