Add / Delete pages to ViewPager dynamically

前端 未结 9 1110
囚心锁ツ
囚心锁ツ 2021-01-29 23:17

I would like to add or delete pages from my view pager dynamically. Is that possible?

9条回答
  •  再見小時候
    2021-01-30 00:19

    Yes. You can add or delete views dynamically to the PagerAdapter that is supplying them to the ViewPager and call notifyDataSetChanged() from the PagerAdapter to alert the affected ViewPager about the changes. However, when you do so, you must override the getItemPosition(Object) of the PagerAdapter, that tells them whether the items they are currently showing have changed positions. By default, this function is set to POSITION_UNCHANGED, so the ViewPager will not refresh immediately if you do not override this method. For example,

    public class mAdapter extends PagerAdapter {
        List mList;
    
        public void addView(View view, int index) {
            mList.add(index, view);
            notifyDataSetChanged();
        }
    
        public void removeView(int index) {
            mList.remove(index);
            notifyDataSetChanged();
        }
    
        @Override
        public int getItemPosition(Object object)) {
            if (mList.contains(object) {
                return mList.indexOf(object);
            } else {
                return POSITION_NONE;
            }
        }
    }
    

    Although, if you simply want to add or remove the view temporarily from display, but not from the dataset of the PagerAdapter, try using setPrimaryItem(ViewGroup, int, Object) for going to a particular view in the PagerAdapter's data and destroyItem(ViewGroup, int, Object) for removing a view from display.

提交回复
热议问题