gpt4 book ai didi

android - 从 fragment 的参数包中保存/检索 parcelable 时的对象引用

转载 作者:行者123 更新时间:2023-11-30 02:14:16 25 4
gpt4 key购买 nike

我有一个 StudentList fragment ,它有一个列表; Student 类实现了 Parcelable;单击 StudentList fragment 中的项目会调用以下 StudentFragment:

public static StudentFragment newInstance(Student student_) {
StudentFragment fragment = new StudentFragment();
Bundle args = new Bundle();
args.putParcelable("STUDENT", student_);
fragment.setArguments(args);
return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args != null) {
mStudent = args.getParcelable("STUDENT");
}
}

private void setStudentName(String newName_) {
mStudent.setName(newName_);
}

这个 fragment 是从另一个“StudentList” fragment 实例化而来的,它有一个列表;他的列表中的一个对象作为参数提供给 StudentFragment.newInstance()。

令我惊讶的是,“StudentFragment”中对 mStudent 的任何更改都会自动反射(reflect)在相应的对象上。进一步检查 StudentFragment 的 onCreate 方法,我发现 mStudent 对象引用与传递给 newInstance 的对象引用相同。

当我单步执行代码时,我发现从未调用过 Student.writeToParcel。

这怎么可能?当我调用 mStudent = args.getParcelable("STUDENT") 时,我不应该得到一个新的对象引用吗?

“arguments”bundle 或 Parcelable 接口(interface)是否保留了一些指向对象引用的链接,并将 parcel/unparceling 用作最后的手段?

最佳答案

This post指出不能保证向 Bundle 写入/读取 Bundle 会导致打包/取消打包。此外,它指出人们不应该假设任何一种行为。这可能就是为什么我总是在 onCreate 中取回完全相同的引用。

关于android - 从 fragment 的参数包中保存/检索 parcelable 时的对象引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29624588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com