首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >谷歌地图不会重组Android

谷歌地图不会重组Android
EN

Stack Overflow用户
提问于 2021-10-25 13:39:51
回答 1查看 69关注 0票数 1

我正在使用AndroidView() composable构建地图,并在地图上放置位置标记,这些标记来自viewModel内部的流。

该列表将在api调用成功后更新。

问题是,即使流发出一个新值,AndroidView()也不会重组。

例如,如果我使用一个可组合的Text,并将流中的值放入其中,它将重新组合。

这是我用来创建Google地图的代码:

代码语言:javascript
复制
@Composable
fun MapView() {
    val mapView = rememberMapWithLifecycle()
    val viewModel: HomeViewModel = hiltViewModel<HomeViewModelImpl>()
    val nearbyCars = viewModel.nearbyCars.collectAsState()
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .fillMaxHeight()
    ) {
        val coroutineScope = rememberCoroutineScope()

            AndroidView(factory = {
                mapView
            }) {
                coroutineScope.launch {
                    val map = it.awaitMap()
                    map.uiSettings.isZoomControlsEnabled = true
                    nearbyCars.value.forEach { location ->
                        val marker = MarkerOptions().title(location.toString()).position(location)
                        map.addMarker(marker)
                    }
                }
            }
        }
}

我一直在关注this tutorial,因为似乎有相当多关于Compose +谷歌地图的文章。

EN

回答 1

Stack Overflow用户

发布于 2021-10-26 12:03:48

您需要提供更新回调。The AndroidView recomposes whenever a State read within the callback changes.

代码语言:javascript
复制
@Composable
fun CustomView() {
    val selectedItem = remember { mutableStateOf(0) }

    // Adds view to Compose
    AndroidView(
        modifier = Modifier.fillMaxSize(), // Occupy the max size in the Compose UI tree
        factory = { context ->
            // Creates custom view
            CustomView(context).apply {
                // Sets up listeners for View -> Compose communication
                myView.setOnClickListener {
                    selectedItem.value = 1
                }
            }
        },
        update = { view ->
            // View's been inflated or state read in this block has been updated
            // Add logic here if necessary

            // As selectedItem is read here, AndroidView will recompose
            // whenever the state changes
            // Example of Compose -> View communication
            view.coordinator.selectedItem = selectedItem.value
        }
    )
}

对于谷歌地图和作曲,我偶然发现了这个compose-sample。但对于更复杂的场景,您可以查看Mitch's solution

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69709092

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档