Kotlin: How to call getSupportFragmentManager() in RecyclerView.Adapter


I would like to call the Support Fragment Manager in my RecyclerView.Adapter after the click event in order to move to a different fragment. My approach:

(context as MainActivity).supportFragmentManager
                            .replace(MainActivity.FRAGMENT_CONTAINER, TextScreen())

But I get the following error:

kotlin.TypeCastException: null cannot be cast to non-null type

Can you help me?


This is because your Context instance in the adapter is not guaranteed to be an Activity. It could potentially be a ContextWrapper holding the Activity as a base Context. Attempting to unwrap this would be fragile.

Instead, I would recommend that you define an interface in your adapter. From your Activity, provide an implementation of this interface to your adapter that will perform the FragmentTransaction. For example:

class MyAdapter : RecyclerView.Adapter<MyType> {
    private var listener: (() -> Unit)?  null

    fun setListener(listener: (() -> Unit)?) {
        this.listener  listener

    // wherever your onClick is handled:

Then, in the Activity that’s initializing MyAdapter:

myAdapter.setListener {
        .replace(MainActivity.FRAGMENT_CONTAINER, TextScreen())

Answered By – Kevin Coppock

Leave a Comment