我正在开发一个类似日记的应用程序,其片段包含一个日历,在此下面是一个viewpager。我使用两个库: 1.水平日历,Mulham-Raee 2. Devlight / InfiniteCycleViewPager viewpager可以在两个方向(左侧和右侧)无限滚动,使用+5000000等太多页面实现此模拟。 我已经连接了日历监听器和寻呼机监听器,这样当用户滚动页面时,日期选项卡也会这样做,反之亦然。 问题是我有一个从sqlite db加载数据的加载器,我希望该片段加载与相应日期匹配的数据。请参阅以下内容 app image
首先,这是我的页面监听器:
@Override
public void onPageSelected(int position) {
//this method changes the current date in the calendar when the page
changes
//this is done changing the value of the current day
update_calendar_position(position);
//change the calendar day with the updated current_day
horizontalCalendar.selectDate(new Date(current_day),true);
mDateListener.getCurrentDate(current_day);
}
在这里,我可以获得页面的位置,但适配器仅使用3个片段进行回收。现在这里是寻呼机的适配器:
public class MyPagerAdapter extends SmartFragmentStatePagerAdapter {
private static int NUM_ITEMS = 3;
public MyPagerAdapter(FragmentManager fragmentManager){
super(fragmentManager);
}
// Returns total number of pages
@Override
public int getCount() {
return NUM_ITEMS;
}
// Returns the fragment to display for that page
@Override
public Fragment getItem(int position) {
switch (position) {
case 0: // Fragment # 0 - This will show FirstFragment
{
return FirstFragment.newInstance(0, "Page # 1", 0);
}
case 1: // Fragment # 0 - This will show FirstFragment different title
{
return FirstFragment.newInstance(1, "Page # 2", 1);
}
case 2: // Fragment # 1 - This will show SecondFragment
{
return FirstFragment.newInstance(2, "Page # 3", 2);
}
default: {
return null;
}
}
}
// Returns the page title for the top indicator
@Override
public CharSequence getPageTitle(int position) {
return "Page " + position;
}
}
我尝试从该位置获取片段,但是onPageSelected方法中页面的位置是5000000,4999999,4999998 5000001,依此类推。但是片段的适配器位置只是0,1,2,并且这些片段的位置在没有精确的情况下发生变化。这个适配器扩展了这个机制:
public abstract class SmartFragmentStatePagerAdapter extends FragmentStatePagerAdapter {
// Sparse array to keep track of registered fragments in memory
private SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
public SmartFragmentStatePagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
// Register the fragment when the item is instantiated
@Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
// Unregister when the item is inactive
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
// Returns the fragment for the position (if instantiated)
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
在寻呼机内部的片段类中,加载器需要日期来过滤正确的数据。我怎样才能做到这一点?
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(getContext(), MyContract.CONTENT_URI,
null,"date=?",new String[]{Long.toString(current_day},null);
//return a cursor with data of current date
}