PlaceAutocompleteFragment - null 不能转换为非 null 类型 (Kotlin)



我正在尝试按照此处的官方文档将放置自动完成片段添加到我的片段中

我收到错误kotlin.TypeCastException: null cannot be cast to non-null type com.google.android.gms.location.places.ui.PlaceAutocompleteFragment

我知道 PlaceAutocompleteFragment 不能设置为 null,所以我尝试在我的getAutoCompleteSearchResults()中添加一个 if 语句来检查 fragmentManager != null,但仍然没有运气

AddLocationFragment.kt

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    getAutoCompleteSearchResults()
}
private fun getAutoCompleteSearchResults() {
        val autocompleteFragment =
            fragmentManager?.findFragmentById(R.id.place_autocomplete_fragment2) as PlaceAutocompleteFragment
        autocompleteFragment.setOnPlaceSelectedListener(object : PlaceSelectionListener {
            override fun onPlaceSelected(place: Place) {
                // TODO: Get info about the selected place.
                Log.i(AddLocationFragment.TAG, "Place: " + place.name)
            }
            override fun onError(status: Status) {
                Log.i(AddLocationFragment.TAG, "An error occurred: $status")
            }
        })
    }
}

片段的 XML:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/darker_gray"
        tools:context=".AddLocationFragment" tools:layout_editor_absoluteY="81dp">
    <fragment
            android:id="@+id/place_autocomplete_fragment2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
            android:theme="@style/AppTheme"
            app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/etAddress"
            app:layout_constraintEnd_toEndOf="parent"/>
</android.support.constraint.ConstraintLayout>

实际上错误在这里:

val autocompleteFragment = fragmentManager?.findFragmentById(R.id.place_autocomplete_fragment2) as PlaceAutocompleteFragment

你正在将可为 null 的对象强制转换为非 null 接收器类型。

溶液:

使强制转换可为空,以便强制转换永远不会失败,但提供如下所示的空对象

val autocompleteFragment = fragmentManager?.findFragmentById(R.id.place_autocomplete_fragment2) as? PlaceAutocompleteFragment // Make casting of 'as' to nullable cast 'as?'

所以现在,您的autocompleteFragment对象变为可为空

我想通了。由于我试图在片段中查找片段,因此我必须执行以下操作:

val autocompleteFragment =
        activity!!.fragmentManager.findFragmentById(R.id.place_autocomplete_fragment2) as PlaceAutocompleteFragment

我们需要获取父活动

最新更新