1. 程式人生 > >Android PagerAdapter 不重新整理、未重新整理,索引超出、檢視重疊問題解決

Android PagerAdapter 不重新整理、未重新整理,索引超出、檢視重疊問題解決

1、第一個問題,一開始呼叫 notifyDataSetChanged 檢視沒有重新整理,
查資料說是要重寫 getItemPosition return POSITION_NONE。

2、第二個問題 destroyItem 方法銷燬時候的程式碼一開始寫成

     View view = mList.get(position);
        container.removeView(view);

會出現索引超出或者檢視重疊等問題,於是改成

 View view = (View) object;
            container.removeView(view);

詳見:


public class BasePagerAdapter<T extends View> extends PagerAdapter {
    private List<T> mList = new ArrayList<>();

    @Override
    public int getItemPosition(@NonNull Object object) {
        //解決無法重新整理的問題
//        return super.getItemPosition(object);
        return POSITION_NONE;
    }

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
//        return super.instantiateItem(container, position);
        View view = mList.get(position);
        container.addView(view);
        return view;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
//        super.destroyItem(container, position, object);
       /* refreshData時候 有 bug,mList變動了,destroyItem 非同步執行,導致部分檢視無法 remove 掉
        View view = mList.get(position);
        container.removeView(view);*/
        if (object instanceof View) {
            View view = (View) object;
            container.removeView(view);
        }
    }


    public void refreshData(List<T> dataList) {
        mList.clear();
        mList.addAll(dataList);
        notifyDataSetChanged();
    }


    public void addDataList(List<T> dataList) {
        mList.addAll(dataList);
        notifyDataSetChanged();
    }

  
    public void addData(T data) {
        mList.add(data);
        notifyDataSetChanged();
    }
}