Update ViewPager dynamically?

后端 未结 20 3087
时光说笑
时光说笑 2020-11-22 02:00

I can\'t update the content in ViewPager.

What is the correct usage of methods instantiateItem() and getItem() in FragmentPagerAdapter class?

I was using onl

相关标签:
20条回答
  • 2020-11-22 02:37

    This might be of help to someone - in my case when inserting a new page the view pager was asking for the position of an existing fragment twice, but not asking for the position of the new item, causing incorrect behaviour and data not displaying.

    1. Copy the source for for FragmentStatePagerAdapter (seems to have not been updated in ages).

    2. Override notifyDataSetChanged()

      @Override
      public void notifyDataSetChanged() {
          mFragments.clear();
          super.notifyDataSetChanged();
      }
      
    3. Add a sanity check to destroyItem() to prevent crashes:

      if (position < mFragments.size()) {
          mFragments.set(position, null);
      }
      
    0 讨论(0)
  • 2020-11-22 02:40

    I've gone through all the answers above and a number of others posts but still couldn't find something that worked for me (with different fragment types along with dynamically adding and removing tabs). FWIW following approach is what worked for me (in case anyone else has same issues).

    public class MyFragmentStatePageAdapter extends FragmentStatePagerAdapter {
        private static final String TAB1_TITLE = "Tab 1";
        private static final String TAB2_TITLE = "Tab 2";
        private static final String TAB3_TITLE = "Tab 3";
    
        private ArrayList<String> titles = new ArrayList<>();
        private Map<Fragment, Integer> fragmentPositions = new HashMap<>();
    
    
        public MyFragmentStatePageAdapter(FragmentManager fm) {
            super(fm);
        }
    
    
        public void update(boolean showTab1, boolean showTab2, boolean showTab3) {
            titles.clear();
    
            if (showTab1) {
                titles.add(TAB1_TITLE);
            }
            if (showTab2) {
                titles.add(TAB2_TITLE);
            }
            if (showTab3) {
                titles.add(TAB3_TITLE);
            }
            notifyDataSetChanged();
        }
    
    
        @Override
        public int getCount() {
            return titles.size();
        }
    
        @Override
        public Fragment getItem(int position) {
            Fragment fragment = null;
    
            String tabName = titles.get(position);
            if (tabName.equals(TAB1_TITLE)) { 
                fragment =  Tab1Fragment.newInstance();
            } else if (tabName.equals(TAB2_TITLE)) {
                fragment =  Tab2Fragment.newInstance();
            } else if (tabName.equals(TAB3_TITLE)) {
                fragment =  Tab3Fragmen.newInstance();
            } 
    
            ((BaseFragment)fragment).setTitle(tabName);
            fragmentPositions.put(fragment, position);
            return fragment;
        }
    
        @Override
        public CharSequence getPageTitle(int position) {
            return titles.get(position);
        }
    
        @Override
        public int getItemPosition(Object item) {
            BaseFragment fragment = (BaseFragment)item;
            String title = fragment.getTitle();
            int position = titles.indexOf(title);
    
            Integer fragmentPosition = fragmentPositions.get(item);
            if (fragmentPosition != null && position == fragmentPosition) {
                return POSITION_UNCHANGED;
            } else {
                return POSITION_NONE;
            }
        }
    
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            super.destroyItem(container, position, object);
            fragmentPositions.remove(object);
        }
    }
    
    0 讨论(0)
  • 2020-11-22 02:41

    Instead of returning POSITION_NONE from getItemPosition() and causing full view recreation, do this:

    //call this method to update fragments in ViewPager dynamically
    public void update(UpdateData xyzData) {
        this.updateData = xyzData;
        notifyDataSetChanged();
    }
    
    @Override
    public int getItemPosition(Object object) {
        if (object instanceof UpdateableFragment) {
            ((UpdateableFragment) object).update(updateData);
        }
        //don't return POSITION_NONE, avoid fragment recreation. 
        return super.getItemPosition(object);
    }
    

    Your fragments should implement UpdateableFragment interface:

    public class SomeFragment extends Fragment implements
        UpdateableFragment{
    
        @Override
        public void update(UpdateData xyzData) {
             // this method will be called for every fragment in viewpager
             // so check if update is for this fragment
             if(forMe(xyzData)) {
               // do whatever you want to update your UI
             }
        }
    }
    

    and the interface:

    public interface UpdateableFragment {
       public void update(UpdateData xyzData);
    }
    

    Your data class:

    public class UpdateData {
        //whatever you want here
    }
    
    0 讨论(0)
  • 2020-11-22 02:41

    I have encountered this problem and finally solved it today, so I write down what I have learned and I hope it is helpful for someone who is new to Android's ViewPager and update as I do. I'm using FragmentStatePagerAdapter in API level 17 and currently have just 2 fragments. I think there must be something not correct, please correct me, thanks. enter image description here

    1. Serialized data has to be loaded into memory. This can be done using a CursorLoader/AsyncTask/Thread. Whether it's automatically loaded depends on your code. If you are using a CursorLoader, it's auto-loaded since there is a registered data observer.

    2. After you call viewpager.setAdapter(pageradapter), the adapter's getCount() is constantly called to build fragments. So if data is being loaded, getCount() can return 0, thus you don't need to create dummy fragments for no data shown.

    3. After the data is loaded, the adapter will not build fragments automatically since getCount() is still 0, so we can set the actually loaded data number to be returned by getCount(), then call the adapter's notifyDataSetChanged(). ViewPager begin to create fragments (just the first 2 fragments) by data in memory. It's done before notifyDataSetChanged() is returned. Then the ViewPager has the right fragments you need.

    4. If the data in the database and memory are both updated (write through), or just data in memory is updated (write back), or only data in the database is updated. In the last two cases if data is not automatically loaded from the database to memory (as mentioned above). The ViewPager and pager adapter just deal with data in memory.

    5. So when data in memory is updated, we just need to call the adapter's notifyDataSetChanged(). Since the fragment is already created, the adapter's onItemPosition() will be called before notifyDataSetChanged() returns. Nothing needs to be done in getItemPosition(). Then the data is updated.

    0 讨论(0)
  • 2020-11-22 02:42

    When using FragmentPagerAdapter or FragmentStatePagerAdapter, it is best to deal solely with getItem() and not touch instantiateItem() at all. The instantiateItem()-destroyItem()-isViewFromObject() interface on PagerAdapter is a lower-level interface that FragmentPagerAdapter uses to implement the much simpler getItem() interface.

    Before getting into this, I should clarify that

    if you want to switch out the actual fragments that are being displayed, you need to avoid FragmentPagerAdapter and use FragmentStatePagerAdapter.

    An earlier version of this answer made the mistake of using FragmentPagerAdapter for its example - that won't work because FragmentPagerAdapter never destroys a fragment after it's been displayed the first time.

    I don't recommend the setTag() and findViewWithTag() workaround provided in the post you linked. As you've discovered, using setTag() and findViewWithTag() doesn't work with fragments, so it's not a good match.

    The right solution is to override getItemPosition(). When notifyDataSetChanged() is called, ViewPager calls getItemPosition() on all the items in its adapter to see whether they need to be moved to a different position or removed.

    By default, getItemPosition() returns POSITION_UNCHANGED, which means, "This object is fine where it is, don't destroy or remove it." Returning POSITION_NONE fixes the problem by instead saying, "This object is no longer an item I'm displaying, remove it." So it has the effect of removing and recreating every single item in your adapter.

    This is a completely legitimate fix! This fix makes notifyDataSetChanged behave like a regular Adapter without view recycling. If you implement this fix and performance is satisfactory, you're off to the races. Job done.

    If you need better performance, you can use a fancier getItemPosition() implementation. Here's an example for a pager creating fragments off of a list of strings:

    ViewPager pager = /* get my ViewPager */;
    // assume this actually has stuff in it
    final ArrayList<String> titles = new ArrayList<String>();
    
    FragmentManager fm = getSupportFragmentManager();
    pager.setAdapter(new FragmentStatePagerAdapter(fm) {
        public int getCount() {
            return titles.size();
        }
    
        public Fragment getItem(int position) {
            MyFragment fragment = new MyFragment();
            fragment.setTitle(titles.get(position));
            return fragment;
        }
    
        public int getItemPosition(Object item) {
            MyFragment fragment = (MyFragment)item;
            String title = fragment.getTitle();
            int position = titles.indexOf(title);
    
            if (position >= 0) {
                return position;
            } else {
                return POSITION_NONE;
            }
        }
    });
    

    With this implementation, only fragments displaying new titles will get displayed. Any fragments displaying titles that are still in the list will instead be moved around to their new position in the list, and fragments with titles that are no longer in the list at all will be destroyed.

    What if the fragment has not been recreated, but needs to be updated anyway? Updates to a living fragment are best handled by the fragment itself. That's the advantage of having a fragment, after all - it is its own controller. A fragment can add a listener or an observer to another object in onCreate(), and then remove it in onDestroy(), thus managing the updates itself. You don't have to put all the update code inside getItem() like you do in an adapter for a ListView or other AdapterView types.

    One last thing - just because FragmentPagerAdapter doesn't destroy a fragment doesn't mean that getItemPosition is completely useless in a FragmentPagerAdapter. You can still use this callback to reorder your fragments in the ViewPager. It will never remove them completely from the FragmentManager, though.

    0 讨论(0)
  • 2020-11-22 02:42

    Use FragmentStatePagerAdapter instead of FragmentPagerAdapter if you want to recreate or reload fragment on index basis For example if you want to reload fragment other than FirstFragment, you can check instance and return position like this

     public int getItemPosition(Object item) {
        if(item instanceof FirstFragment){
           return 0;
        }
        return POSITION_NONE;
     }
    
    0 讨论(0)
提交回复
热议问题