Android ViewPager删除当前页面并移至下一页

时间:2017-08-14 01:25:20

标签: java android android-viewpager notifydatasetchanged current-page

当用户点击删除按钮时,在ViewPager中,我正在尝试删除当前页面并转到下一页。 当我尝试下面的代码时,它移动到下一页但删除了最后一页。请帮助我。

@Override
public Object instantiateItem(ViewGroup container, final int IdxVal)
{
    LinearLayout linearLayout = new LinearLayout(context);
    linearLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

    ImageView imageView = new ImageView(context);
    imageView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

    Glide.with(context)
            .load(imageListAryVar.get(IdxVal))
            .fitCenter()
            .into(imageView);

    linearLayout.addView(imageView);
    container.addView(linearLayout);

    return linearLayout;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object)
{
    container.removeView((LinearLayout) object);
}

void delCurrentPageFnc()
{
    int delIdxVar = viewPager.getCurrentItem();

    if(imageListAryVar.size() > 1)
    {
        if (delIdxVar == imageListAryVar.size() - 1)
            viewPager.setCurrentItem(delIdxVar - 1);
        else
            viewPager.setCurrentItem(delIdxVar + 1);

        imageListAryVar.remove(delIdxVar);
        notifyDataSetChanged();
    }
    else finish();
}

1 个答案:

答案 0 :(得分:1)

经过几次尝试,我通过添加getItemPosition并设置返回POSITION_NONE来解决此问题; 如果你不添加这个notifyDataSetChanged();方法不起作用。

@Override
public int getItemPosition(Object object)
{
    return POSITION_NONE;
}

void delCurrentPageFnc()
{
    int delIdxVar = viewPager.getCurrentItem();

    if(imageListAryVar.size() > 1)
    {
        imageListAryVar.remove(delIdxVar);
        notifyDataSetChanged();
    }
    else finish();
}
设置getItemPosition后,这是不必要的,所以删除了

if (delIdxVar == imageListAryVar.size() - 1) 
    viewPager.setCurrentItem(delIdxVar - 1);
else 
   viewPager.setCurrentItem(delIdxVar + 1);