androidandroid-fragmentsandroid-ktx

Add fragment following Android Developer Documentation not working?


I recently found on https://developer.android.com/guide/fragments/create, the way to create fragment as below, when we have implementation "androidx.fragment:fragment-ktx:1.4.0"

enter image description here

However, after following all the steps there, I still get an error on the add as shown below

enter image description here

I can easily fix it using

            supportFragmentManager.commit {
                setReorderingAllowed(true)
                add(R.id.container, MainFragment())
            }

But curious why is it not working? Did I miss anything?

Just to provide the context, my imports are as below

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.activityfragmentviewmodel.ui.main.MainFragment
import androidx.fragment.app.commit

And my library dependencies are

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.0'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.2'
    implementation "androidx.fragment:fragment-ktx:1.4.0"
    implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.4.0'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0'

Solution

  • The reified add method that the documentation uses is an extension method, which means you need to import it, just like your commit extension method you've imported:

    import androidx.fragment.app.add