Update ViewPager dynamically?

后端 未结 20 3395
时光说笑
时光说笑 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: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
    }
    

提交回复
热议问题