android - 从 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
}
解决方案
在您的活动中实现 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()
}
推荐阅读
- javascript - 有没有办法将 URLFetchApp.fetch 从 gs 端传递到 javascript 端
- reactjs - 如何在不遍历状态的情况下访问减速器中的 redux 状态数组属性
- sql-server - 数据透视表包含额外的 NULL 行
- powerbi - 如何获取使用指标(查看次数)
- matlab - 如果这个变量在调用之间发生了变化,为什么匿名函数的固定参数没有更新?
- ios - UICollectionView 自定义布局页脚视图不粘在集合视图的底部
- python - 如何在matplolib图中找到多条线的交点
- angular - 在Angular + Typescript中存储复选框和输入元素的值数组
- jquery - 如何在 à foreach 循环内的 jQuery 代码中定位 ACF 字段?
- javascript - 当我将它分成另一个组件时,React-router Redirect 似乎不起作用