0

在ViewPager中,當用戶單擊刪除按鈕時,我試圖刪除當前頁面並移到下一頁。 當我嘗試下面的代碼時,它移動到下一頁,但刪除最後一頁。請幫助我。Android 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(); 
} 
+0

你可以嘗試,如果你刪除你的'如果(delIdxVar == imageListAryVar.size() - 1) viewPager.setCurrentItem(delIdxVar - 1); else viewPager.setCurrentItem(delIdxVar + 1);'? –

+0

如果我刪除它,頁面將不會自動移動到下一頁 –

+0

notifyDataSetChanged();將不會調用instantiateItem(); –

回答

0

經過幾次嘗試後,我通過添加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); 
相關問題