Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android viewpager change adapter

I'm developing an app with a ViewPager for lateral scrolling tables, sometimes i need to change the adapter to load a different set of tables. I've tried to do the following:

mViewPager.setAdapter(new pagerAdapterPushed(getSupportFragmentManager()));
mViewPager.getAdapter().notifyDataSetChanged();
indicator.setViewPager(mViewPager);
indicator.invalidate();
mViewPager.invalidate();

but it always reload the previous data. Isn't it possibile to change the adapter of a ViewPager?

like image 363
Ste Avatar asked Oct 08 '12 14:10

Ste


People also ask

How do I update my Android ViewPager adapter?

Firstly set viewpager adapter to null then recreate the adapter and set i to it to viewpager. Show activity on this post. Define which message which is needed to update.

What is ViewPager adapter in android?

ViewPager in Android allows the user to flip left and right through pages of data. In our android ViewPager application we'll implement a ViewPager that swipes through three views with different images and texts.

Is ViewPager deprecated?

This function is deprecated.


2 Answers

Exactly like my APP doing...

For change ViewPagerAdapter, what I did is :

  1. Clear all Fragments inside current adapter

  2. Set current adapter to null

  3. Assign new adpater for ViewPager

    /* Clear all Fragments inside current adapter */
    public class MyPagerAdapter extends FragmentPagerAdapter
    {
      private ArrayList<Fragment> fragments = new ArrayList<Fragment>();
      //...some stuff
    
      public void clearAll() //Clear all page
      {
        for(int i = 0; i < fragments.size(); i ++)
        fragMan.beginTransaction().remove(fragments.get(i)).commit();
        fragments.clear();
      }
    }
    
    /* Set current adapter to null */
    Constants.VP.removeAllViews();
    Constants.VP.setAdapter(null);
    
    /* Assign new adpater for ViewPager */
    Constants.PAGER = new MyPagerAdapter(getSupportFragmentManager());
    Constants.VP.setAdapter(Constants.PAGER);
    

Hope it helps~

like image 135
RRTW Avatar answered Sep 22 '22 19:09

RRTW


You need to override public int getItemPosition (Object object) in pager adapter. For every element in the viewpager, you need to return POSITION_UNCHANGED (if it is still in the pager) or POSITION_NONE (if it was removed). Otherwise the view pager won't know something has changed. I wouldn't recommend setting a new adapter, just clearing out the data in the old one.

like image 26
mark.kedzierski Avatar answered Sep 22 '22 19:09

mark.kedzierski