如何将数据传递给 BottomSheetDialogFragment

7

我正在使用 RecyclerView 显示数据。当我点击列表项时,会启动 BottomSheetDialogFragment

如何在 Kotlin 中将列表项数据传递给 BottomSheetDialogFragment?

 BottomSheetFragment().show(context!!.supportFragmentManager, "BottomSheetFragment")

class BottomSheetFragment() : BottomSheetDialogFragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        var view = inflater.inflate(R.layout.coin_detail_lauout, container, false)
        return view
    }
}
1个回答

17

使用 Bundle

    val bottomSheetFragment = BottomSheetFragment()
    val bundle = Bundle()
    bundle.putString("key", data)
    bottomSheetFragment.arguments = bundle

关于ViewHolder类的说明

 inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    val textView = itemView.textView!!

    init {
        itemView.setOnClickListener {
            showBottomSheet(itemView.context, list.get(layoutPosition))
        }
    }

    private fun showBottomSheet(context: Context, data: String) {

        val bottomSheetFragment = BottomSheetFragment()
        val bundle = Bundle()
        bundle.putString("key", data)
        bottomSheetFragment.arguments = bundle

        bottomSheetFragment.show(
            (context as AppCompatActivity).supportFragmentManager,
            "bottomSheetFragment"
        )
    }

}

在你的BottomSheetFragmentonCreateView方法中

arguments?.getString("key")

BottomSheetFragment

class BottomSheetFragment : BottomSheetDialogFragment() {

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    val view = inflater.inflate(R.layout.fragment_bottomsheetfragment_list_dialog, container, false)
    val data =  arguments?.getString("key")
//  Log.d("===",data+"")
    return view
    }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接