如何为PagerAdapter实现视图回收机制?

Mor*_*lus 29 android convertview android-viewpager android-pageradapter

我有一个寻呼机适配器,假设膨胀表示日历的复杂视图.

每年的日历需要大约350毫秒才能充气.

为了提高性能,我想实现ListView回收视图(convertView参数输入getView())的数组适配器中存在的相同机制.

这是getView()来自适配器的电流.

@Override
protected View getView(VerticalViewPager pager, final DateTileGrid currentDataItem, int position)
{
    mInflater = LayoutInflater.from(pager.getContext());

        // This is were i would like to understand weather is should use a recycled view or create a new one.
    View datesGridView = mInflater.inflate(R.layout.fragment_dates_grid_page, pager, false);


    DateTileGridView datesGrid = (DateTileGridView) datesGridView.findViewById(R.id.datesGridMainGrid);
    TextView yearTitle = (TextView) datesGridView.findViewById(R.id.datesGridYearTextView);
    yearTitle.setText(currentDataItem.getCurrentYear() + "");
    DateTileView[] tiles = datesGrid.getTiles();

    for (int i = 0; i < 12; i++)
    {
        String pictureCount = currentDataItem.getTile(i).getPictureCount().toString();
        tiles[i].setCenterLabel(pictureCount);
        final int finalI = i;
        tiles[i].setOnCheckedChangeListener(new DateTileView.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(DateTileView tileChecked, boolean isChecked)
            {
                DateTile tile = currentDataItem.getTile(finalI);
                tile.isSelected(isChecked);
            }
        });
    }

    return datesGridView;
}
Run Code Online (Sandbox Code Playgroud)

实现这种行为的任何指针或方向?特别是如何在适配器中知道其中一个DateTileGridViews正在刷屏幕,以便我可以将其保存在内存中以便下次重用.

Mor*_*lus 32

所以我已经弄清楚了.

  1. 覆盖destroyItem(ViewGroup container, int position, Object view)ans保存缓存视图
  2. 创建一个单独的方法,以查看是否有机会使用循环视图或是否应该为新视图充气.
  3. 请记住,一旦使用了再循环视图,就会从缓存中删除它,以避免同一视图将相同视图附加到寻呼机.

这是代码..我使用Stack of view来缓存我的寻呼机中所有被删除的视图

private View inflateOrRecycleView(Context context)
{

    View viewToReturn;
    mInflater = LayoutInflater.from(context);
    if (mRecycledViewsList.isEmpty())
    {
        viewToReturn = mInflater.inflate(R.layout.fragment_dates_grid_page, null, false);
    }
    else
    {
        viewToReturn = mRecycledViewsList.pop();
        Log.i(TAG,"Restored recycled view from cache "+ viewToReturn.hashCode());
    }


    return viewToReturn;
}

@Override
public void destroyItem(ViewGroup container, int position, Object view)
{
    VerticalViewPager pager = (VerticalViewPager) container;
    View recycledView = (View) view;
    pager.removeView(recycledView);
    mRecycledViewsList.push(recycledView);
    Log.i(TAG,"Stored view in cache "+ recycledView.hashCode());
}
Run Code Online (Sandbox Code Playgroud)

不要忘记在适配器构造函数中实例化堆栈.