I want to show a map using OSMdroid. I have a singleton to create the MapView:
object MapViewSingleton {
private var mapView: MapView? = null
fun getMapView(context: Context): MapView {
if (mapView == null) {
mapView = createMapView(context)
}
return mapView!!
}
private fun createMapView(context: Context): MapView {
if (mapView != null) {
if (mapView!!.parent != null) {
(mapView!!.parent as ViewGroup).removeView(mapView)
}
}
val mapView = MapView(context)
Configuration.getInstance().load(context, PreferenceManager.getDefaultSharedPreferences(context))
Configuration.getInstance().userAgentValue = "Test"
mapView.setTileSource(TileSourceFactory.MAPNIK)
mapView.setMultiTouchControls(true)
return mapView
}
}
I use this composable function to show the map:
@Composable
fun OsmdroidMapView() {
val mapView = MapViewSingleton.getMapView(LocalContext.current)
AndroidView(
modifier = Modifier.fillMaxSize(),
factory = {
mapView
}
)
}
The map is shown on the display when its the first time i go on the map tab. When i switch to another tab and come back the map tab, the map disappeared. I can now see only an empty grid.
This is the way I implemented the tabs:
val items = listOf(
BottomNavigationItem(
route = "settings",
title = "Einstellungen",
selectedIcon = Icons.Filled.Settings,
unselectedIcon = Icons.Outlined.Settings
),
BottomNavigationItem(
route = "map",
title = "Karte",
selectedIcon = Icons.Filled.Place,
unselectedIcon = Icons.Outlined.Place
),
BottomNavigationItem(
route = "data",
title = "Daten",
selectedIcon = Icons.Filled.Done,
unselectedIcon = Icons.Outlined.Done
)
)
var selectedItemIndex by rememberSaveable { mutableStateOf(0) }
val navController = rememberNavController()
Scaffold(
bottomBar = {
NavigationBar {
items.forEachIndexed { index, item ->
NavigationBarItem(
selected = selectedItemIndex == index,
onClick = {
selectedItemIndex = index
navController.navigate(item.route)
},
label = {
Text(text = item.title)
},
icon = {
BadgedBox(badge = {}) {
Icon(
imageVector = if (index == selectedItemIndex) {
item.selectedIcon
} else item.unselectedIcon,
contentDescription = item.title
)
}
}
)
}
}
}
) {
NavHost(navController = navController, startDestination = "settings") {
composable("map") {
OsmdroidMapView()
}
composable("settings") {
Settings()
}
composable("data") {
Data()
}
}
}
Can anyone see the mistake I did and tell me why i can only see an empty grid after switching tabs?