android viewpager change adapter

后端 未结 4 2046
花落未央
花落未央 2021-02-02 14:46

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:<

相关标签:
4条回答
  • 2021-02-02 15:21

    Add this to view pager to reload for next fragment:

    viewPager.setCurrentItem()
    
    0 讨论(0)
  • 2021-02-02 15:25

    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~

    0 讨论(0)
  • 2021-02-02 15:32

    I see that @RRTW way worked for some people but it did not do the trick for me (although it was close). Without commitNow() instead of regular commit() it would not work properly. I did something like that:

    private fun changePagerAdapter(newAdapter: PagerAdapter) {
    
        val transaction = supportFragmentManager.beginTransaction()
            supportFragmentManager.fragments.forEach {
            transaction.remove(it)
        }
    
        transaction.commitNow()
        view_pager.adapter = newAdapter
    }
    
    0 讨论(0)
  • 2021-02-02 15:36

    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.

    0 讨论(0)
提交回复
热议问题