Parcelable对象在状态恢复后是否保留其引用

时间:2015-06-21 11:55:29

标签: android android-fragments memory-management reference parcelable

所以我想知道Parcelables是否从活动传递到片段然后重新创建将在重新创建活动/片段后具有相同的引用?

考虑一下我有这个活动:

public class MainActivity extends Activity {

    ArrayList<Item> items = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        MyFragment fragment = new MyFragment();

        if (savedInstanceState == null) {
            items.add(new Item(1));
            items.add(new Item(2));
            items.add(new Item(3));

            Bundle args = new Bundle();
            args.putParcelableArrayList("fragment_arg_items", items);
            fragment.setArguments(args);
        } else {
            items = savedInstanceState.getParcelableArrayList("activity_state_items");
        }

        getFragmentManager().beginTransaction().add(fragment, "fragment").commit();
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelableArrayList("activity_state_items", items);
    }

}

这个片段:

public class MyFragment extends Fragment {

    Item item;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Newly created
        Bundle args = getArguments();
        if (args != null) {
            ArrayList<Item> items = args.getParcelableArrayList("fragment_arg_items");
            item = items.get(1);
        }

        // Restored
        if (savedInstanceState != null) {
            item = savedInstanceState.getParcelable("item");
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelable("item", item);
    }

}

Item只是一个可以分配的类,它的构造函数接受一个int参数。

我的问题是:一旦重新创建了活动和片段,它们是否会对项目具有相同的引用?当系统内存不足时,这还包括活动的破坏吗?

0 个答案:

没有答案