Add / Delete pages to ViewPager dynamically

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

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

9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-30 00:09

    Yes, the code should be like this:

    public int addPage(View view, int position) {
            if ((position >= 0) && (position < getSize())) {
                myPagerAdapter.mListViews.add(position, view);
                myPagerAdapter.notifyDataSetChanged();
                return position;
            } else {
                return -1;
            }
        }
    
    public View removePage(int position) {
            if ((position < 0) || (position >= getSize()) || (getSize()<=1)) {
                return null;
            } else {
                if (position == mPager.getCurrentItem()) {
                    if(position == (getSize()-1)) {
                        mPager.setCurrentItem(position-1);
                    } else if (position == 0){
                        mPager.setCurrentItem(1);
                    }
                }
                View tempView = myPagerAdapter.mListViews.remove(position);
                myPagerAdapter.notifyDataSetChanged();
                return tempView;
            }
        }
    

    But there is a bug. If the current Item is 0, and to remove page 0, it will not refresh the screen instantly, I haven't found a solution for this.

提交回复
热议问题