Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
738 views
in Technique[技术] by (71.8m points)

android - ViewPager set current page programmatically

I wrote a custom ViewPager to disable Swipe Scroll, but I want to swipe programmatically. I have three Tab in my view pager, but when I call viewPager.setCurrentItem(viewPager.getCurrentItem()+1) on the first Fragment, it moves to the third Fragment instead of the second Fragment. And if I call same function in the second Fragment, it goes to the third. If I call (viewPager.getCurrentItem()-1)` in the third fragment, it works fine by moving back. Any help would be appreciated. My code is below:

NonSwipeAbleViewPager

public class NonSwipeableViewPager extends ViewPager {

private boolean swipeable;

public NonSwipeableViewPager(Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyViewPager);
    try {
        swipeable = a.getBoolean(R.styleable.MyViewPager_swipeable, true);
    } finally {
        a.recycle();
    }
}

@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
    return swipeable ? super.onInterceptTouchEvent(event) : false;
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    return swipeable ? super.onTouchEvent(event) : false;
}
}

Declaration in XML

<co.example.customview.NonSwipeableViewPager
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    app:swipeable="false" />

Calling it

 @Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.menuNext:
            NonSwipeableViewPager pages = (NonSwipeableViewPager) getActivity().findViewById(R.id.pager);
            pages.setCurrentItem(pages.getCurrentItem()+1, true);
            break;
        default:
            return super.onOptionsItemSelected(item);
    }
    return super.onOptionsItemSelected(item);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
viewPager.setCurrentItem(idx);

where idx is 0 based integer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...