natario
natario

Reputation: 25204

Dynamically changing fragment contents in a ViewPager

I have:

So my code was:

public class StatsPagerAdapter extends FragmentPagerAdapter {
    static final int FRAGMENT_COUNT = 5;
    private Parameters[] sectionData;

    public StatsPagerAdapter(FragmentManager manager) {
        super(manager);
        this.sectionData = new Parameters[FRAGMENT_COUNT];
    }

    @Override
    public Fragment getItem(int position) {
        return StatsSectionFragment.getInstance(this.sectionData[position]);
    }

    @Override
    public int getCount() {
        return FRAGMENT_COUNT;
    }

    public void setSectionData(int position, Parameters sectionData) {
        this.sectionData[position] = sectionData;
        notifyDataSetChanged();
    }
}

So I'm passing sectionData[position] to the getInstance() method of my generic sub-fragment. That data should differentiate each instance of the fragments loaded into the ViewPager.

At first I'll be passing an empty reference, but then in my async class:

    @Override
    protected void onProgressUpdate(Parameters... sectionValues) {
        super.onProgressUpdate(sectionValues);
        mPagerAdapter.setSectionData(sectionId, sectionValues[0]);
    }

That should call the setSectionData() above, update sectionData[position] and generate a call to notifiyDataSetChanged(). I was hoping that doing so would make the adapter retrieve all its items again, thus calling getItem() again, and loading new fragments.

Sadly it does not. So right now:

How can I reload content into those already-there fragments, or force the adapter to call getItem() and update its views?

Upvotes: 1

Views: 1752

Answers (1)

mmlooloo
mmlooloo

Reputation: 18977

Add this to your adapter:

@Override
public int getItemPosition(Object object){
    return PagerAdapter.POSITION_NONE;
}

This make your adapter call getItem again when you call notifyDataSetChanged();

Upvotes: 1

Related Questions