我有一个带有一些参数的 Serializable
SpecialObject(位置等依次为 Serializable
)
我想通过处理一个 SpecialObject
对象,通过一个活动( MySpecialActivity
)打开一个片段( MySpecialFragment
) . 它到目前为止工作,我可以触发并打开 MySpecialFragment
但 SpecialObject
没有正确处理 . 我觉得我看不到森林里的树木了 .
调试它:
val PARAM_BUNDLE = "bundle_extra"
val PARAM_SPECIAL_EXTRA = "special_bundle_extra"
class MySpecialActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_my_special)
val sameIntentSht = intent // same as getIntent()
val extras = intent.extras // same as getIntent().getExtras()
val bundleExtras = intent.getBundleExtra(PARAM_BUNDLE)
val extras2 = sameIntentSht.extras
val bundleExtras2 = sameIntentSht.getBundleExtra(PARAM_BUNDLE)
if(extras != null && extras2 != null && bundleExtras != null && bundleExtras2 != null) Timber.d("Jzst for debugging")
FragmentHelper.inflateFragment(this, R.id.fragmentContainer, MySpecialFragment::class.java, extras)
}
companion object {
fun createIntent(context: Context,
mySpecial: MySpecialObject?): Intent {
val intent = Intent(context, MySpecialActivity::class.java)
val bundle = Bundle()
mySpecial?.let {
bundle.putSerializable(PARAM_SPECIAL_EXTRA, mySpecial)
}
intent.putExtra(PARAM_BUNDLE, bundle)
// intent.flags = FLAG_ACTIVITY_NEW_TASK
return intent
}
}
}
Instantiation createIntent() :创建Intent以启动MySpecialActivity createIntent()
方法正常工作 . 当我进入intent对象时,它有它的bundle,而它又有了Serializable MySpecialObject对象 .
Unpacking the Bundle onCreate() :正如你在
中看到的那样,所有额外的*和bundleExtra *对象都没有mMap
直接来自getIntent()的getExtras()(在Kotlin的intent.extras中)与sameIntentSht不同,这显然是相同的 val sameIntentSht = intent
. 你在调试中看到intent.extras有652个字节,sameIntentSht.extras有604个字节!??!?
How can I handle over this bundle properly?
编辑:我使用了RubenGees的建议 . 到目前为止工作:
val intent = Intent(context, MySpecialActivity::class.java)
mySpecial?.let {
intent.putExtra(PARAM_SPECIAL_EXTRA, mySpecial)
}
// intent.flags = FLAG_ACTIVITY_NEW_TASK
return intent
但是在onCreate上我不得不将意图复制到sameIntentsht:
见 mMap
和 extra2
!
1 回答
几件事:
在原始代码中你没有必要 . 您可以直接在Intent上调用
putExtra
.调用
intent.extras
或intent.getExtras()
会创建extras包的副本 . 所以预计你会得到两个不同的包 .预计在调试时,
extras
已空mMap
. Bundle具有惰性语义,只有访问数据的第一个调用才会对其进行解组,从而填充mMap
.我猜你最初创建的Intent包含一个包含Bundle的Bundle,但在访问时你试图跳过一步 . 我建议删除现有代码并重新开始:
使用
intent.putExtra(EXTRA_SPECIAL, specialObject)
方法创建Intent并放置特殊数据;然后通过调用
intent.getSerializableExtra(EXTRA_SPECIAL)
检索特殊数据 .这就是这里所需要的一切 .