1

我的 xml-pager 文件中已经有两个按钮“左”和“右”。我想设置它们:当我点击“左”按钮时,页面自动向左滑动,当我点击“右”按钮时它会自动向右移动.. 有人可以给我代码以放入我的活动文件吗?谢谢你!

4

2 回答 2

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);
}
于 2013-01-13T16:10:51.880 回答
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() 来获取当前页面的索引

于 2014-05-08T02:43:20.550 回答