欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Fragment好Activity之间的数据交换(传值)

程序员文章站 2022-03-30 09:01:10
...

1、Activity把数据传递给Fragment

有时候从Activity跳转到fragment时需要传递参数,可以使用bundle的方式传递

Activity中代码

private fun initView() {
        fragments = ArrayList()
        if (fragments!!.isEmpty()) {
            fragments!!.add(MineRelationDiscoverFragment().newInstance(userId, imgUrl!!))
            fragments!!.add(MineRelationQuestionFragment().newInstance(userId, imgUrl!!))
        }
        view_pager.adapter = FragmentPagerAdapter(supportFragmentManager, fragments!!, titles)
        view_pager.offscreenPageLimit = 2
        tab.tabMode = TabLayout.MODE_FIXED
        tab.tabGravity = TabLayout.GRAVITY_FILL
        tab.run { setupWithViewPager(view_pager) }

    }

fragment中代码

fun newInstance(userId: Int, imgUrl: String): MineRelationDiscoverFragment {
        val frag = MineRelationDiscoverFragment()
        val bundle = Bundle()
        bundle.putInt("userId", userId)
        bundle.putString("imgUrl", imgUrl)
        frag.arguments = bundle
        return frag
    }


//取参数  onViewCreated()方法中
override fun initEnv() {
        userId = arguments!!.getInt("userId")
        imgUrl = arguments!!.getString("imgUrl")
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        super.initEnv()
    }

2、Fragment传递参数给Activity

使用接口回调的方式传递给Activity

Fragment代码

 private var myListener: MineDiscoverListener? = null
    override fun onAttach(context: Context?) {
        super.onAttach(context)
        myListener = activity as MineDiscoverListener
    }


interface MineDiscoverListener {
        fun sendDiscoverIds(idList: List<Int>)
    }

参考:陈李冠

https://blog.csdn.net/chenliguan/article/details/53906934