gon*_*250 1 android google-maps kotlin
我正在尝试在一个片段中实现一个地图,并且能够显示该地图,但onMapReady由于未添加标记并且不移动相机,因此无法正常工作。
码
MapFragment
class MapFragment : Fragment(), OnMapReadyCallback {
private lateinit var mMap: GoogleMap
companion object {
var mapFragment : SupportMapFragment?=null
val TAG: String = MapFragment::class.java.simpleName
fun newInstance() = MapFragment()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
var rootView = inflater.inflate(R.layout.fragment_map, container, false)
mapFragment = fragmentManager?.findFragmentById(R.id.fallasMap) as SupportMapFragment?
mapFragment?.getMapAsync(this)
return rootView
}
override fun onMapReady(googleMap: GoogleMap?) {
mMap = googleMap!!
// Add a marker in Sydney and move the camera
val sydney = LatLng(-34.0, 151.0)
mMap.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
}
}
Run Code Online (Sandbox Code Playgroud)
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=".fragments.MapFragment">
<fragment
android:id="@+id/fallasMap"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
Run Code Online (Sandbox Code Playgroud)
您使用了错误的片段管理器来访问它。由于是片段中的片段,因此将其添加到中childFragmentManager。
childFragmentManager.findFragmentById(R.id.fallasMap) as SupportMapFragment
Run Code Online (Sandbox Code Playgroud)
还可以使用as?强制转换运算符,而不是强制转换为可选类型。甚至进行常规转换,因为您需要正确的片段并且null可能是错误。
如果未正确清理片段,也不要存储对该片段的静态引用。