我在网上发现了这段代码,并试图在我的项目中进行测试。我的项目使用一个数据库,我想在每条记录之间滑动,所以我认为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;
}
}发布于 2014-03-05 07:16:45
这就是修改代码的方法
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);https://stackoverflow.com/questions/22188804
复制相似问题