简体   繁体   中英

ViewPager - update view after adapter got empty

I'm using a FragmentStatePagerAdapter with a ViewPager .

Everything is working fine. If I open my activity with an empty Adapter, the ViewPager is empty, if I add items, the ViewPager updates correctly.

BUT, if I open my activity and delete the last item of my ViewPager , the ViewPager does not invalidate correctly and keeps the last Fragment visible.

How can I avoid this?

I'm using my library, it's a wrapper class for ViewPager + ViewPagerIndicator + FragmentPager(State)Adapter:

It implements a simple FragmentStatePagerAdapter with weak references to it's fragments...

My code looks like following:

mPagerManager = new MPagerManager<ExerciseViewFragment, MFragmentPagerStateAdapter<ExerciseViewFragment>>(pager, tpi,
            new MFragmentPagerStateAdapter<ExerciseViewFragment>(fragmentManager)
            {
                @Override
                public CharSequence getPageTitle(int pos)
                {
                    return mData.workout.getWExercise().get(pos).getExercise().getName();
                }

                @Override
                public int getCount()
                {
                    return mData.workout.getWExercise().size();
                }

                @Override
                public ExerciseViewFragment createFragment(int pos)
                {
                    return ExerciseViewFragment.newInstance(pos, mData.workout.getWExercise());
                }
            });

I'm calling mPagerManager.notifyDataSetChanged(); which forwards the call to the FragmentPagerStateAdapter directly...

PS: I know, I can make it invisible, if item count is 0... But I'm wondering if there's a better solution

This is an old question but I thought you might still need to know what to do. It's very common issue. ViewPager does not invalid views which are already created(including these which are ready on the left and right side of your current view). Solving this is very easy. Just implement the following method in your adapter like this:

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

By default this method returns PagerAdapter.POSITION_UNCHANGED.

For most developers this method usage is misleading, I had this problem myself till I realised that this method is used by ViewPager.dataSetChanged() to establish which items should be recreated. With above code you tell ViewPager to recreate all items whenever data set change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM