类型不匹配。要求:片段,找到:PlaceAutocompleteFragment

Type mismatch. Required: Fragment, Found: PlaceAutocompleteFragment

我碰到了一个

Duplicate ID, tag null, or parent id with another fragment for placeAutocompleteFragment

错误,所以我按照这个 solution 尝试通过使用 childFragmentManager

的片段事务添加 placeAutocompleteFragment 来修复它

片段classonCreateView

val fm: FragmentManager = childFragmentManager
var placeAutocompleteFragment: PlaceAutocompleteFragment? = fm.findFragmentByTag("placeAutocompleteFragment") as PlaceAutocompleteFragment?

if (placeAutocompleteFragment == null){
    placeAutocompleteFragment = PlaceAutocompleteFragment()
    fm.beginTransaction().add(R.id.address_layout, placeAutocompleteFragment, "placeAutocompleteFragment").commit()
}

.xml

<android.support.constraint.ConstraintLayout
...
...
...
    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/address_layout"
        android:background="@drawable/rounded_search_bar"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.0"
        android:layout_marginTop="8dp" app:layout_constraintTop_toTopOf="parent"
        android:orientation="horizontal">
    </LinearLayout>
...
...
...
</android.support.constraint.ConstraintLayout>

现在的问题是上线

fm.beginTransaction().add(R.id.address_layout, placeAutocompleteFragment, "placeAutocompleteFragment").commit()

我收到 placeAutocompleteFragment 类型不匹配的类型错误。需要:片段,找到:PlaceAutocompleteFragment?

有什么建议吗?

谢谢

问题

getChildFragmentManager 将return 支持 FragmentManager 的库版本。所以你应该传递继承支持库版本的片段对象。

但是PlaceAutocompleteFragment继承android.app.Fragment.

解决方案

使用 SupportPlaceAutocompleteFragment 代替 PlaceAutocompleteFragment。