skip to Main Content

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

2

Answers


  1. 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"

    Login or Signup to reply.
  2. 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
            }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search