我的xml-pager文件中已经有两个按钮“left”和“right”。 我想设置它们:当我点击“向左”按钮时,页面自动向左滑动,当我点击“向右”按钮时它会自动向右移动..有人可以给我代码放入我的活动文件吗?谢谢!
答案 0 :(得分:8)
要转到下一页/上一页,请使用以下内容:
private void nextPage() {
int currentPage = viewPager.getCurrent();
int totalPages = viewPager.getAdapter().getCount();
int nextPage = currentPage+1;
if (nextPage >= totalPages) {
// We can't go forward anymore.
// Loop to the first page. If you don't want looping just
// return here.
nextPage = 0;
}
viewPager.setCurrentItem(nextPage, true);
}
private void previousPage() {
int currentPage = viewPager.getCurrent();
int totalPages = viewPager.getAdapter().getCount();
int previousPage = currentPage-1;
if (previousPage < 0) {
// We can't go back anymore.
// Loop to the last page. If you don't want looping just
// return here.
previousPage = totalPages - 1;
}
viewPager.setCurrentItem(previousPage, true);
}
答案 1 :(得分:1)
对于android.support.v4,您可以使用以下内容:
ViewPager pager;
pager = (ViewPager) findViewById(R.id.viewPager);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
有一个像这样的veiwpager适配器类:
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int pos) {
switch(pos)
{
case 0: return WelcomeFrag1.newInstance("Page 1");
case 1: return WelcomeFrag2.newInstance("Page 2");
case 2: return WelcomeFrag3.newInstance("Page 3");
case 3: return WelcomeFrag4.newInstance("Page 4");
case 4: return WelcomeFrag5.newInstance("Page 5");
default: return WelcomeFrag1.newInstance("Page 1");
}
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return 5;
}
}
最后有两个方法nextPage()和previousPage()如下:
private void nextPage() {
int currentPage = pager.getCurrentItem();
int totalPages = pager.getAdapter().getCount();
int nextPage = currentPage+1;
if (nextPage >= totalPages) {
// We can't go forward anymore.
// Loop to the first page. If you don't want looping just
// return here.
nextPage = 0;
}
pager.setCurrentItem(nextPage, true);
}
private void previousPage() {
int currentPage = pager.getCurrentItem();
int totalPages = pager.getAdapter().getCount();
int previousPage = currentPage-1;
if (previousPage < 0) {
// We can't go back anymore.
// Loop to the last page. If you don't want looping just
// return here.
previousPage = totalPages - 1;
}
pager.setCurrentItem(previousPage, true);
}
请注意:我使用getCurrentItem()来获取当前页面的索引