Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

android - FragmentPagerAdapter - How to handle Orientation Changes?

I use a FragmentPagerAdapter containing several Fragments that need to be notified about changes to the database. I do this by iterating over the fragments, which implement a callback interface, and calling a refreshData() method.

This works just fine until the device changes orientation. After an orientation change, the fragment UI does not visibly refresh even though the method call seems to work.

From what I have read so far this occurs because the FragmentPagerAdapter handles the fragment life-cycle and the fragments that receive the callback are not the ones that are actually displayed.

private class DataPagerAdapter extends FragmentPagerAdapter {

    private DataFragment[] fragments = new DataFragment[] {
                                     new FooDataFragment(), BarDataFragment()};

    public DataPagerAdapter(android.support.v4.app.FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return fragments[position];
    }

    @Override
    public int getCount() {
        return fragments.length;
    }

    public DataFragment[] getFragments() {
        return fragments;
    }
}

protected void refreshData() {
    for (DataFragment dataFragment : mPagerAdapter.getFragments()) {
     dataFragment.refreshData();
}

I temporarily fixed this issue using a broadcast receiver inside each fragment, but this solution seems to be wasteful and might create memory leaks. How to I fix this properly? I use a different layout and logic in landscape mode so I want to use the newly created fragments after an orientation change.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes like you said FragmentManager handles fragments after orientation change so getItem in adapter is not called. But you can override method instantiateItem() which is called even after orientation change and cast Object to Fragment and save it in your array.

 @Override
 public Object instantiateItem(ViewGroup container, int position) {
     DataFragment fragment = (DataFragment) super.instantiateItem(container, position);
     fragments[position] = fragment;
     return fragment;
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...