1

My application has a view pager including three fragments. These are managed by a FragmentPagerAdapter.

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Fragment page adapter
        mainFragmentPagerAdapter = new MainFragmentPagerAdapter(getSupportFragmentManager());

        // Set the view pagers adapter
        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        viewPager.setAdapter(mainFragmentPagerAdapter);

        // Set up the TabLayout using the view pager
        TabLayout tabLayout = (TabLayout) findViewById(R.id.fixed_tabs);
        tabLayout.setupWithViewPager(viewPager);
}

Things start to get complicated when all of these Fragments contain a RecyclerView that can be updated.

To correctly pass data to the Fragments, I'm using the newInstance method shown below:

public static InformationFragment newInstance() {
        Bundle arguments = new Bundle();
        // Put arguments here.
        InformationFragment fragment = new InformationFragment();
        fragment.setArguments(arguments);
        return fragment;
}

I then have another method inside InformationFragment to update the arguments when required:

public void updateData() {

    Bundle arguments = getArguments();
    // Put arguments
    this.adapter.updateItems(items);
}

Data that can be used to populate the RecyclerView needs to be of multiple types (some android, some custom). Therefore, I have ArrayList<Object> items; containing all my objects.

My question is, what is the best way to store this ArrayList in a bundle so it can be used by a fragment?

I am able to do the following, but it feels dirty:

public void updateData(ArrayList<Object> items) {
        getArguments().putSerializable("items", items);
        this.adapter.updateItems(items);
    }

and then retrieve by:

if (arguments.containsKey("items")) {
            ArrayList<Object> items = (ArrayList<Object>)arguments.getSerializable("items");
}

Or is there a better approach?


I think the problem is that

bond.to_cash_flows()

is a method call and the output (and it's attributes) can't change by assignment in the way you've done. That is, the line

bond.to_cash_flows().amounts = bond.to_cash_flows().amounts.append(series)

has no effect. You could do something like

amounts = bond.to_cash_flows().amounts.append(Series)
print('SERIES', amounts)

Not sure this will solve the problem as I don't know the context but it will print what you want in the example

4

1 回答 1

0

我建议不要保留 aList<Object>而是将多个列表放入您的捆绑包中。此外,将您的对象作为可序列化的对象放入包中确实并没有那么糟糕,但是如果您想以更安卓的方式进行操作,您可以为存储在该包中的每个对象实现 Parcelable 接口。

于 2015-08-13T16:43:50.443 回答