android - Jetpack Compose - 在配置更改时保留 AndroidView 的状态

标签 android android-jetpack-compose

很可能是一个新手问题,因为我对 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/

相关文章:

android - Jetpack Compose onClick 波纹不以圆周运动传播?

android - 如何使用 MaterialTheme 覆盖 Jetpack Compose 中 TextField 中的文本颜色?

android - 为什么我在 Jetpack Compose 中收到 "Optional Modifier parameter should have a default value of Modifier"警告?

android - 使用表面 View 时闪烁

java - 如何发现两个物体之间的角度?

java - 如何从 Activity 中提取Android服务中的字符串值?

android - android程序如何删除刚拍的照片

android - Android Studio 2.0 AVD 管理器中缺少 API 14 和 15

android - 尝试在将一个 Activity 更改为第二个 Activity 后保存编辑文本字段的值,然后返回到 jetpack compose 中的第一个 Activity

android - 具有由 Hilt 在仪器测试零参数构造函数中注入(inject)的可组合项的真实 ViewModel