Search code examples
androidkotlinfragmentbundledialogfragment

Kotlin android data transfer from fragment to dialogFragment


I want to pass some data from Fragment to a DialogFragment (when I click a view by using onClickListener), but the data has empty values in Dialog.

While debugging I found that VO data has no problem. (log comments in my code works correctly)

So, I think that I am not using Bundle correctly.

What can I do to solve this problem?

AccountFragment.class (recyclerview bindViewHolder)

 override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val accountVO = list[position]
        val viewHolder = holder as AccountViewHolder

        viewHolder.text_account_title.text = accountVO.title
        viewHolder.text_account_bank.text = accountVO.bank
        viewHolder.text_account_account.text = accountVO.account
        viewHolder.text_account_name.text = accountVO.name

        viewHolder.text_account.setOnClickListener() {
            // log
            // Toast.makeText(context, "${accountVO.title}, ${accountVO.content}", Toast.LENGTH_SHORT).show()
            val accountFragment = AccountFragment()
            val bundle = Bundle()
            bundle.putString("title", accountVO.title)
            bundle.putString("content", accountVO.content)
            accountFragment.arguments = bundle
            AccountDetailDialogFragment().show(activity?.supportFragmentManager as FragmentManager, "dialog_event")
        }

    }

AccountDetailDialogFragment

class AccountDetailDialogFragment : DialogFragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    val view = inflater.inflate(R.layout.activity_account_detail_dialog_fragment, container, false)
    view.text_account_detail_title.text = arguments?.getString("title")
    view.text_account_detail_content.text = arguments?.getString("content")

    isCancelable = false

    return view
}

}


Solution

  • You didn't actually set the arguments on your AccountDetailDialogFragment, you set it on your accountFragment (which you didn't even use):

    val bundle = Bundle()
    bundle.putString("title", accountVO.title)
    bundle.putString("content", accountVO.content)
    val dialogFragment = AccountDetailDialogFragment()
    dialogFragment.arguments = bundle
    dialogFragment.show(requireActivity().supportFragmentManager, "dialog_event")
    

    Note that you should make sure your AccountDetailDialogFragment uses the right import for its superclass (you shouldn't need to cast the supportFragmentManager).