wbk727
wbk727

Reputation: 8408

Using fragmentManager in RecyclerView adapter click event

With the deprecation of FragmentManager, Android Studio desn't provide any code suggestions for the deprecated code.

The problem is fragmentManager in val manager = (holder.itemView.context as Activity).fragmentManager as it returns this error:

'getter for fragmentManager: FragmentManager!' is deprecated. Deprectaed in Java

I'm already using import androidx.fragment.app.DialogFragment but the issuee still doesn't go away. Also, I've already seen this question, but it's not clear on what should be used instead in Kotlin.

holder.myButton.setOnClickListener {
    val dialog = MyDialogFragment()
    val manager = (holder.itemView.context as Activity).fragmentManager
    dialog.show(manager, "example")
}

Upvotes: 0

Views: 1175

Answers (1)

Wojciech Januszek
Wojciech Januszek

Reputation: 651

According to the documentation, you should get the support manager instead. You'll just have to cast the context to FragmentActivity instead of Activity, like this:

val manager = (holder.itemView.context as FragmentActivity).supportFragmentManager

EDIT: Make sure that MyDialogFragment extends androidx.fragment.app.DialogFragment, not android.app.DialogFragment. Your Activity should also extend AppCompatActivity (or at least FragmentActivity) to make it work correctly.

Upvotes: 3

Related Questions