【发布时间】:2021-12-18 13:11:53
【问题描述】:
所以我想要的是当用户从溢出菜单中选择“配置文件”时启动一个新活动(ProfileActivity),并且我想同时将一些数据传递给该 ProfileActivity。 如何正确地将数据从片段传输到不是片段本身容器的另一个活动?我执行以下操作:
1- 创建接口
interface IProfileToActivity {
fun profileInfo(data: AllHeroes.Global)
}
2- 然后我在activity中继承
class ProfileActivity : AppCompatActivity(), IProfileToActivity {
private lateinit var myBinding: ActivityProfileBinding
override fun profileInfo(data: AllHeroes.Global) {
myBinding.tvUsername.text = data.name
myBinding.tvDivision.text = data.rank.rankName
Log.i("Apex Info 3", data.toString())
}
}
3- 从片段发送
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
(activity as? IProfileToActivity)?.profileInfo(allInfoApexResponse.global)
mHeroesAdapter.heroesList(allAdapterListHero)
}
点击菜单中的 Profile 按钮后,数据应该转移到另一个活动中
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId){
R.id.action_profile -> {
(activity as? IProfileToActivity)?.profileInfo(testApex)
startActivity(Intent(requireActivity(), ProfileActivity::class.java))
return true
}
}
return super.onOptionsItemSelected(item)
}
但是什么也没发生,为什么?我做错了什么?
【问题讨论】:
-
How to properly transfer data from a fragment to another activity that is not a container of the fragment itself?活动包含片段,所以某处你是带着意图开始这个活动的,对吧?将数据传递给该意图 -
@a_local_nobody 我需要打包吗?或者只是如何发送意图?如果我从片段本身做它会有多正确?
-
这能回答你的问题吗? Passing Data Between Fragments to Activity
标签: android kotlin android-fragments android-activity