我正在關注本指南: https ://developers.google.com/codelabs/maps-platform/maps-platform-101-android#9
我正在嘗試在片段中獲取地圖。我的地圖已成功運行,但現在當地圖打開時,它默認以真正高級視圖顯示非洲。我希望地圖默認在本地級別上向我的城市開放。
我的片段的 xml 檔案如下所示:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ViewNearbyFragment">
<androidx.fragment.app.FragmentContainerView
xmlns:map="http://schemas.android.com/apk/res-auto"
class="com.google.android.gms.maps.SupportMapFragment"
map:mapId="{my_map_id}"
android:id="@ id/map_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
和同一個片段對應的 Kotlin 檔案看起來像:
class ViewNearbyFragment : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
(fragmentManager?.findFragmentById(
R.id.map_fragment
) as? SupportMapFragment)?.getMapAsync { googleMap ->
// Ensure all places are visible in the map.
googleMap.setOnMapLoadedCallback {
val bounds = LatLngBounds.builder()
bounds.include(LatLng(0.0, 0.0))
googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds.build(), 20))
}
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_view_nearby, container, false)
}
}
我從來沒有進入 getMapAsync 呼叫之后的塊,我不知道為什么。如何訪問在 xml 檔案中創建的地圖?或者更好的是,如何更改與此地圖關聯的默認值?
uj5u.com熱心網友回復:
您的代碼有兩個問題:
onCreate()onCreateView根據片段生命周期指南運行之前。這意味著當您的代碼運行時,您FragmentContainerView還沒有被夸大(并且您SupportFragmentFragment還沒有被創建) 。onCreate您要運行的代碼onCreateView應移至onViewCreated().您使用了錯誤的 FragmentManager - 已棄用
fragmentManager的是FragmentManager片段附加到的那個(這就是為什么不推薦使用更具描述性的parentFragmentManager名稱的原因)。您創建的片段是“子片段”(根據FragmentManager 指南),因此您需要使用childFragmentManager.
您的固定代碼如下所示:
class ViewNearbyFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_view_nearby, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
(childFragmentManager.findFragmentById(
R.id.map_fragment
) as? SupportMapFragment)?.getMapAsync { googleMap ->
// Ensure all places are visible in the map.
googleMap.setOnMapLoadedCallback {
val bounds = LatLngBounds.builder()
bounds.include(LatLng(0.0, 0.0))
googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds.build(), 20))
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/470147.html
