首页 > 解决方案 > 从 Activity 向 Fragment 传递接口

问题描述

我正在尝试将信息从片段发送到主要活动。

我正在尝试var interfaceName在主要活动的片段中设置 a 。

我创建var menuInterface: MenuInterface并尝试将其设置为onNavigationItemSelected使用 myFragment.menuInterface = this

由于menuInterface某种原因保持为空......知道为什么吗?

onNavigationItemSelected

override fun onNavigationItemSelected(menuItem: MenuItem): Boolean {
    when (menuItem.itemId) {
        R.id.feedLayoutId -> {
            feedFragment = FeedFragment()
            feedFragment.menuInterface = this
            barTitle.text = "myTitle"
            supportFragmentManager
                .beginTransaction()
                .replace(R.id.frame_layout, feedFragment)
                .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                .commit()
        }
    }
    drawerLayout.closeDrawer(GravityCompat.START)
    return true
}

标签: androidkotlin

解决方案


在您的活动中实现 MenuInterface,并从您的代码中删除此行。

feedFragment.menuInterface = this

在你的片段中:

private var menuInterface: MenuInterface? = null

override fun onAttach(context: Context?) {
    super.onAttach(context)
    menuInterface = context as MenuInterface
}

override fun onDetach() {
    menuInterface = null
    super.onDetach()
}

推荐阅读