2014-11-05 52 views
2

我正在實現可正常工作的FragmentStatePagerAdapter,但getItem(int位置)始終沒有正確的值。FragmentStatePagerAdapter.getItem()返回錯誤的位置

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()沒有。任何想法爲什麼?發生這種情況是因爲這些碎片被緩存了嗎?

回答

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); 
    } 
} 
相關問題