我在网上找到了这个代码,并试图在我的项目中测试它。我的项目使用数据库,我想在每个记录之间滑动,所以我认为ViewPager是要走的路。我有我的活动和片段已经工作但我不知道如何将附加的代码实现到我的项目中。我在寻找的是在哪里以及如何使用它?从活动或片段?我该怎么做呢我已经有了一个光标和投影但现在确定两者如何协同工作。我希望我有意义。
public class CursorPagerAdapter<F extends Fragment> extends FragmentStatePagerAdapter {
private final Class<F> fragmentClass;
private final String[] projection;
private Cursor cursor;
public CursorPagerAdapter(FragmentManager fm, Class<F> fragmentClass, String[] projection, Cursor cursor) {
super(fm);
this.fragmentClass = fragmentClass;
this.projection = projection;
this.cursor = cursor;
}
@Override
public F getItem(int position) {
if (cursor == null) // shouldn't happen
return null;
cursor.moveToPosition(position);
F frag;
try {
frag = fragmentClass.newInstance();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
Bundle args = new Bundle();
for (int i = 0; i < projection.length; ++i) {
args.putString(projection[i], cursor.getString(i));
}
frag.setArguments(args);
return frag;
}
@Override
public int getCount() {
if (cursor == null)
return 0;
else
return cursor.getCount();
}
public void swapCursor(Cursor c) {
if (cursor == c)
return;
this.cursor = c;
notifyDataSetChanged();
}
public Cursor getCursor() {
return cursor;
}
}
答案 0 :(得分:0)
这是您修改代码的方式
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction().add(R.id.item_detail_container, fragment).commit();
ViewPager vpPager = (ViewPager) findViewById(R.id.pager);
CursorPagerAdapter<ItemDetailFragment> adapterViewPager = new CursorPagerAdapter(
getSupportFragmentManager(), fragment_class, your_projection, your_cursor);
vpPager.setAdapter(adapterViewPager);