androidandroid-fragmentskotlinplaceautocompletefragmentchild-fragment

Type mismatch. Required: Fragment, Found: PlaceAutocompleteFragment


I bumped into a

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

error, and so i followed this solution to try and fix it by adding the placeAutocompleteFragment via a fragment transaction using the childFragmentManager

fragment class onCreateView

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>

The problem now is on the line

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

I get a type mistake for placeAutocompleteFragment Type mismatch. Required: Fragment, Found: PlaceAutocompleteFragment?

Any suggestions?

Thanks


Solution

  • Problem

    getChildFragmentManager will return support library version of FragmentManager. So you should pass fragment object which inherits support library version of Fragment.

    But PlaceAutocompleteFragment inherits android.app.Fragment.

    Solution

    Using SupportPlaceAutocompleteFragment instead PlaceAutocompleteFragment.