FragmentStatePagerAdapter.getItem()返回错误的位置

时间:2014-11-05 23:02:14

标签: android

我正在实现一个工作正常的FragmentStatePagerAdapter,但是getItem(int position)始终没有正确的值。

public class EventPagerAdapter extends FragmentStatePagerAdapter {
    private static String LOG = "EVENTPAGER";
    private Calendar currentDate;
    public EventPagerAdapter(FragmentManager fm) {
        super(fm);

        currentDate = Calendar.getInstance();
    }

    public void setCurrentDate(Date date) {
        currentDate.setTime(date);
    }

    @Override
    public Fragment getItem(int i) {
        Log.i(LOG, "item " + i);
        // reset Date every time
        currentDate.setTime(new Date());

        SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
        int days = (i > 50 ? i-50 : -50+i);
        currentDate.add(Calendar.DATE, days);           
        String dateFormatted = fmt.format(currentDate.getTime());

        Bundle args = new Bundle();
        args.putString("calendarDate", dateFormatted);

        Fragment fragment = new EventFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getCount() {
        return 100;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        Log.i(LOG, "position " + position);
        int days = 0;
        days = (position > 49 ? position-49 : -49+position);
        currentDate.setTime(new Date());
        currentDate.add(Calendar.DATE, days);  
        SimpleDateFormat fmt = new SimpleDateFormat("E, d.MMM");
        String dateFormatted = fmt.format(currentDate.getTime());

        return dateFormatted;
    }

我希望有100个片段显示片段49,当前日期为第一个片段。向左滑动会将日期增加一天,向右滑动会减少日期。

EventPagerAdapter eventPagerAdapter = new EventPagerAdapter(getSupportFragmentManager());      
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);

viewPager.setAdapter(eventPagerAdapter);
viewPager.setCurrentItem(49);

这适用于具有正确索引的getPageTitle()方法。但getItem()没有。知道为什么吗?这是因为这些片段被缓存了吗?

1 个答案:

答案 0 :(得分:0)

由于getItem()仅针对每个项目调用一次,因此我可以通过实施SparseArray来解决问题。

@Override
public Fragment getItem(int position) {
    Log.i(LOG, "item " + position);
    // reset date every time
    currentDate.setTime(new Date());

    int days = (position > 49 ? position-49 : -49+position);
    currentDate.add(Calendar.DATE, days);           
    String dateFormatted = compareDateFormat.format(currentDate.getTime());

    Bundle args = new Bundle();
    args.putString("calendarDate", dateFormatted);

    EventFragment fragment = new EventFragment();
    fragment.setArguments(args);
    fragments.put(position, fragment);
    return fragment;
}

@Override
public Object instantiateItem(ViewGroup view, int position) {
    EventFragment fragment = fragments.get(position);
    if (fragment != null) {
        return fragment;
    }
    else {
        return super.instantiateItem(view, position);
    }
}