很可能是一个新手问题,因为我对 Android 开发人员还很陌生 - 我在配置更改/导航时在 @Composable 中保留 AndroidView 的状态时遇到了麻烦,因为工厂 block 被调用(如预期的那样)并且我的图表被重新实例化。
@Composable
fun ChartView(viewModel:ViewModel, modifier:Modifier){
val context = LocalContext.current
val chart = remember { DataChart(context) }
AndroidView(
modifier = modifier,
factory = { context ->
Log.d("DEBUGLOG", "chart init")
chart
},
update = { chart ->
Log.d("DEBUGLOG", "chart update")
})
}
DataChart
是具有复杂图表的第 3 方组件,我想保留缩放/滚动状态。我知道我可以使用 ViewModel 在 conf 中保留 UI 状态。变化,但考虑到保存缩放/滚动状态的复杂性,我想问一下是否还有其他更简单的方法来实现这一点?我试图将整个图表实例移动到 viewModel,但由于它使用上下文,我收到有关上下文对象泄漏的警告。
任何帮助,将不胜感激!
最佳答案
如果您想在配置更改时保留 AndroidView 的状态,请使用 rememberSaveable
而是 remember
.
While remember helps you retain state across recompositions, the state is not retained across configuration changes. For this, you must use rememberSaveable. rememberSaveable automatically saves any value that can be saved in a Bundle. For other values, you can pass in a custom saver object.
如果 DataChart 是 Parcelable、Serializable 或其他可以存储在 bundle 中的数据类型:
val chart = rememberSaveable { DataChart(context) }
如果上述方法不起作用,则创建一个 MapSave 来保存数据、缩放/滚动状态...我假设 DataChart 具有您需要保存的 zoomIndex、scrollingIndex、values 属性:fun getDataChartSaver(context: Context) = run {
val zoomKey = "ZoomState"
val scrollingKey = "ScrollingState"
val dataKey = "DataState"
mapSaver(
save = { mapOf(zoomKey to it.zoomIndex, scrollingKey to it.scrollingIndex, dataKey to it.values) },
restore = {
DataChart(context).apply{
zoomIndex = it[zoomKey]
scrollingIndex = it[scrollingKey]
values = it[dataKey]
}
}
)
}
利用:val chart = rememberSaveable(stateSaver = getDataChartSaver(context)){ DataChart(context) }
查看更多 Ways to store state
关于android - Jetpack Compose - 在配置更改时保留 AndroidView 的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67887995/