3

How to force ViewPager to re-instantiate its elements

 2 years ago
source link: https://www.codesd.com/item/how-to-force-viewpager-to-re-instantiate-its-elements.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How to force ViewPager to re-instantiate its elements

advertisements

This question already has an answer here:

  • ViewPager PagerAdapter not updating the View 34 answers

I am using ViewPager to allow user to swipe between its views. Is there a way how to force this ViewPager to reload/re-instantiate its views in case that they are no longer valid or needs to be refreshed? I tried to call notifyDataSetChanged() on its adapter but this does not invoke instantiateItem() method again.

Here is the class that extends from ViewPager and its adapter definision. Bellow is the refresh() method that I call when I want to force to refresh items.

public class DayFlipper extends ViewPager {

public class FlipperAdapter extends PagerAdapter {

    @Override
    public int getCount() {
        return DayFlipper.DAY_HISTORY;
    }

    @Override
    public void startUpdate(View container) {
    }

    @Override
    public Object instantiateItem(View container, int position) {
        Log.d(TAG, "instantiateItem(): " + position);

        Date d = DateHelper.getBot();
        for (int i = 0; i < position; i++) {
            d = DateHelper.getTomorrow(d);
        }

        d = DateHelper.normalize(d);

        CubbiesView cv = new CubbiesView(mContext);
        cv.setLifeDate(d);
        ((ViewPager) container).addView(cv, 0);
        // add map
        cv.setCubbieMap(mMap);
        cv.initEntries(d);
        return cv;
    }

    @Override
    public void destroyItem(View container, int position, Object object) {
        ((ViewPager) container).removeView((CubbiesView) object);
    }

    @Override
    public void finishUpdate(View container) {

    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((CubbiesView) object);
    }

    @Override
    public Parcelable saveState() {
        return null;
    }

    @Override
    public void restoreState(Parcelable state, ClassLoader loader) {

    }

}

    ...

    public void refresh() {
    getAdapter().notifyDataSetChanged();
}
}


Had the same problem. For me it worked to call

viewPage.setAdapter( adapter );

again which caused reinstantiating the pages again.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK