如何识别viewpager的最后一页并在滑动时自动重定向到第一页

时间:2018-11-21 08:35:56

标签: java android android-viewpager

我的标题是我的问题,viewPager中有3页。在ViewPager中的最后一页上滑动时,如何重定向到首页?

ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
    @Override
    public void onPageSelected(int position) {
        int x  = position;
        Log.i("ON Possition",Integer.Tostring(x));
        if(x == 3){
            viewPager.setCurrentItem(x);
            Log.i("ON last Possition",Integer.Tostring());
        }
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {

    }

    @Override
    public void onPageScrollStateChanged(int arg0) {

    }
};

1 个答案:

答案 0 :(得分:0)

您不能从最后一页平滑地移到首页。

阅读下面的代码。我们应该假货。

private class MyPagerAdapter extends PagerAdapter {
    Context context;

    public MyPagerAdapter(Context context) {
        this.context= context;
    }

    @Override
    public int getCount() {
        if (tList != null && tList.size() > 1) {
            return tList.size() * MAX_PAGE; // simulate infinite by big number of products
        } else {
            return tList.size();
        }
    }


    @Override
    public int getItemPosition(Object object) {
        int position;
        if (tList != null && tList.size() > 1) {
            position = super.getItemPosition(object) % tList.size(); // use modulo for infinite cycling
            return position;
        } else {
            return super.getItemPosition(object);
        }

    }

    public int getItemPosition(int index) {
        int position;
        if (tList!= null && tList.size() > 1) {
            position = index % tList.size(); // use modulo for infinite cycling
            return position;
        } else {
            return index;
        }

    }


}