我现在在 android 上 2 周。作为我的第一个项目,我尝试设置一个带有开关和 placeautocompletefragment 的工具栏,然后是一个 mapfragment。所以地图工作正常,工具栏也可以,除了其中的 Placeautocompletefragment 。在调试时,我发现在初始化 Placeautocompletefragment 后它仍然为空。
地点和地图 api 被激活,清单中的关键。
有人可以告诉我,我在哪里犯了错误并告诉我如何解决它?由于 NULL 值,我无法在其上设置侦听器。我在互联网上找到的每个样本都带有 fragmentmanager,自 API 28 起已弃用,因此对我来说实际上没用。
感谢到目前为止。
格雷茨
编辑: ativity_maps.xml
<RelativeLayout 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=".MapsActivity">
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:elevation="20dp"
app:title="Fake GPS"
android:visibility="visible">
<fragment
android:id="@+id/place_autocomplete_fragment"
android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
android:layout_height="wrap_content"
android:layout_width="match_parent"
/>
</android.support.v7.widget.Toolbar>
<fragment android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.SupportMapFragment"/>
Mapsactivity.kot
class MapsActivity : AppCompatActivity(), OnMapReadyCallback {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_maps)
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
val mapFragment = supportFragmentManager
.findFragmentById(R.id.map) as SupportMapFragment
mapFragment!!.getMapAsync(this)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu, menu)
onOffSwitch = menu.findItem(R.id.switchIO).actionView as Switch
onOffSwitch?.setOnCheckedChangeListener { _, isChecked -> (removed code here, cause unnecessary) }
autocompleteFragment = supportFragmentManager.findFragmentById(R.id.place_autocomplete_fragment) as? PlaceAutocompleteFragment
}
}