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

13,213

Solution 1

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:
    listener?.invoke()
}

Then, in the Activity that's initializing MyAdapter:

myAdapter.setListener {
    supportFragmentManager
        .beginTransaction()
        .replace(MainActivity.FRAGMENT_CONTAINER, TextScreen())
        .commit()
}

Solution 2

Updated for 2021 - Kotlin Answer

If you want to call "supportFragmentManager" in Fragment

activity.supportFragmentManager
Share:
13,213

Related videos on Youtube

Simon Giesen
Author by

Simon Giesen

Updated on June 04, 2022

Comments

  • Simon Giesen
    Simon Giesen over 1 year

    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
                                .beginTransaction()
                                .replace(MainActivity.FRAGMENT_CONTAINER, TextScreen())
                                .commit()
    

    But I get the following error:

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

    Can you help me?

    • Omar Mainegra
      Omar Mainegra almost 5 years
      context is null, just make sure to set a value before casting it to MainActivity
    • Murtaza Khursheed Hussain
      Murtaza Khursheed Hussain almost 5 years
      It is a Typecast Exception and it is saying can not be cast to non-null type something which does not allow null you are passing null to it. In Kotlin you need to add ? to make in nullable