我正在使用AndroidView() composable构建地图,并在地图上放置位置标记,这些标记来自viewModel内部的流。
该列表将在api调用成功后更新。
问题是,即使流发出一个新值,AndroidView()也不会重组。
例如,如果我使用一个可组合的Text,并将流中的值放入其中,它将重新组合。
这是我用来创建Google地图的代码:
@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 +谷歌地图的文章。
发布于 2021-10-26 12:03:48
您需要提供更新回调。The AndroidView recomposes whenever a State read within the callback changes.
@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。
https://stackoverflow.com/questions/69709092
复制相似问题