Home > Back-end >  Show DialogFragment in Recyclerview Adapter
Show DialogFragment in Recyclerview Adapter

Time:07-12

I'm trying to use a DialogFragmemt in an adapter, but it doesn't work as planned. I have listed the Dialog class and the adapter below.

DialogFragment (ListsSettings.kt)

class ListsSettings : DialogFragment() {
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        val view: View = inflater.inflate(R.layout.dialog_lists_settings, container, false)      
        return view
    }
}

Adapter (AllListAdapter.kt) -> (onCreateViewHolder)

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.card_all_lists, parent, false)

Show Fragment ->

    view.setOnLongClickListener {
        val activity = context as FragmentActivity
        val dialog = ListsSettings()
        dialog.show(activity.supportFragmentManager, "dialog")
        return@setOnLongClickListener true
    }

    return ViewHolder(view)
}

Error

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.amelie.volvic, PID: 31327
    java.lang.ClassCastException: android.app.Application cannot be cast to androidx.fragment.app.FragmentActivity

CodePudding user response:

try it like this

view.setOnLongClickListener {
    val dialog = ListsSettings()
    dialog.show(context.supportFragmentManager, "dialog")
    return@setOnLongClickListener true
}

if this does not work move this code to "onBindViewHolder"

CodePudding user response:

Try this solution

view.setOnLongClickListener {
            val activity: FragmentActivity = context as FragmentActivity
            val fm: FragmentManager = activity.getSupportFragmentManager()
            val dialog = ListsSettings()
            dialog.show(fm, "dialog")
            return@setOnLongClickListener true
        }
  • Related