ViewPager 导航按钮
Posted
技术标签:
【中文标题】ViewPager 导航按钮【英文标题】:ViewPager navigation buttons 【发布时间】:2013-01-13 15:55:44 【问题描述】:我的 xml-pager 文件中已经有了“左”和“右”两个按钮。 我想设置它们:当我点击“左”按钮时,页面会自动向左滑动,当我点击“右”按钮时,它会自动向右滑动。有人可以给我代码以放入我的活动文件吗?谢谢!
【问题讨论】:
【参考方案1】:要转到下一页/上一页,请使用以下内容:
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);
【讨论】:
感谢您的回答 Joseph.. 我对 android 编程真的很陌生,所以我很抱歉这个问题,但我要把这段代码放在哪里? 把它放到你的UNO.java中,把viewPager
替换成mPager
。【参考方案2】:
对于 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()来获取当前页面的索引
【讨论】:
以上是关于ViewPager 导航按钮的主要内容,如果未能解决你的问题,请参考以下文章
BottomNavigationView+ViewPager+Fragment 底部导航按钮 kotlin版本