Skip to content Skip to sidebar Skip to footer

Android Change Default Direction Swipe Of Viewpager

by default ViewPager swipe direction is left to right to view other tabs with content, now i like to change this direction to right to left. my FragmentPagerAdapter class : public

Solution 1:

ViewPager.setCurrentItem(int pageIndex, boolean isSmoothScroll);

pageIndex is total page count. by doing this user will be forced to swipe from right to left.

Solution 2:

Copy-pasted answer from here

I faced the same problem month ago but I think I found a great solution.

1) Change your TabLayout direction to ltr in xml:

<android.support.design.widget.TabLayout
    android:id="@+id/tl_activity_main"
    android:layout_below="@id/toolbar_activity_main"
    android:layoutDirection="ltr"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    style="@style/DisionTabLayout" />

2) Create custom adapter for ViewPager and override methods getItem(int position) and getPageTitle(int position):

@Overridepublic Fragment getItem(int position) {
    if (mIsRtlOrientation && mTabs != null && mTabs.length > 0) {
        return mTabs[mTabs.length - position - 1].getFragment();
    } else {
        return mTabs[position].getFragment();
    }
}

@OverridepublicintgetCount() {
    return mTabs.length;
}

@Overridepublic CharSequence getPageTitle(int position) {
    if (mIsRtlOrientation && mTabs != null && mTabs.length > 0) {
        return mTabs[mTabs.length - position - 1].getTitle();
    } else {
        return mTabs[position].getTitle();
    }
}

3) Set the adapter to ViewPager and then apply this ViewPager to TabLayout.

privatevoidsetAdapters() {
    // initialize adapter
    mTabsAdapter = new TabsAdapter(getSupportFragmentManager(), mTabs, true);
    // set adapter to ViewPager
    vp.setAdapter(mTabsAdapter);
    // set ViewPager to TabLayout
    tl.setupWithViewPager(vp);
    // if RTL orientation, go to last item
    vp.setCurrentItem(vp.getAdapter().getCount() - 1, false);
}

4) I created a blog post which contains more details and full code - here

Post a Comment for "Android Change Default Direction Swipe Of Viewpager"