【发布时间】:2021-09-08 17:14:53
【问题描述】:
我正在尝试将 Google 地图嵌入到属于另一个 Fragment 的 FragmentContainer 中。
这是我目前所拥有的(API 和凭据工作正常):
DetailsFragment.kt
class DetailsFragment : Fragment() {
private var binding: DetailsFragmentBinding? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
val fragmentBinding = DetailsFragmentBinding.inflate(inflater)
binding = fragmentBinding
return fragmentBinding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding?.apply {
lifecycleOwner = viewLifecycleOwner
}
val mapFragment = fragmentManager?.findFragmentById(R.id.map) as SupportMapFragment?
mapFragment?.getMapAsync(callback)
}
private val callback = OnMapReadyCallback { googleMap ->
val sydney = LatLng(-34.0, 151.0)
googleMap.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
}
}
details_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:bind="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
(...)
<fragment
android:id="@+id/map"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="250dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/property_layout" />
(...)
</layout>
Fragment 正确捕获了 Map Api,但未触发 OnMapReadyCallback,因此我无法设置位置和标记。此代码使用专用 Activity 工作,我尝试使用 Fragment 找到解决方案,但没有运气。这里有什么帮助吗?类型
【问题讨论】:
标签: android google-maps