dvrm
dvrm

Reputation: 3759

how to reverse the direction of viewPager to left to right order?

I have viewPager with several views. the default behavior of viewPager is that the first item is displayed first, then swiping right to left displays the second view right to the current view etc.

the behavior i want is that after the first item is displayed, swiping left to right will display the next view left to the current item.

i searched a lot for clever way to implement this but no results..
thanks in advance.

Upvotes: 5

Views: 10320

Answers (4)

vadiole
vadiole

Reputation: 387

The solution for ViewPager2

I was looking for a way to reverse viewpager2 and came up with this one. It's a dirty hack, but it works

The idea is to mirror the viewpager horizontally, and then mirror each page back

var ViewPager2.isReversedDirection: Boolean
get() = scaleX == -1f
set(value) {
    if (value) {
        scaleX = -1f  //  mirror viewpager

        val listener = object : RecyclerView.OnChildAttachStateChangeListener {
            override fun onChildViewDetachedFromWindow(view: View) = Unit

            override fun onChildViewAttachedToWindow(view: View) {
                view.scaleX = -1f  //  mirror the page back when it was attached
            }
        }

        val recyclerView = getChildAt(0) as RecyclerView
        recyclerView.addOnChildAttachStateChangeListener(listener)
    }
}

Since it depends on the internal implementation of viewpager, it tested on androidx.viewpager2:viewpager2:1.0.0

Upvotes: 0

Ahamadullah Saikat
Ahamadullah Saikat

Reputation: 4644

you can now show items horizontally in Recyclerview.

There have an option to show recyclerview items as reverse order.

RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, true)); // last parameter is isReverse

If you want to show RecyclerView items like ViewPager paging you should to use this library:

https://github.com/lsjwzh/RecyclerViewPager

This codes will show RecyclerView as Reverse Order ViewPager.

Here is the code:

RecyclerViewPager recyclerViewPager = findViewById(R.id.recyclerViewPager);
recyclerViewPager.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, true));


repositories {
    ...
    maven { url "https://jitpack.io" }
    ...
}

dependencies {
    ...
    compile 'com.github.lsjwzh.RecyclerViewPager:lib:v1.1.2@aar'
    ...
}

Upvotes: 0

Paul Lammertsma
Paul Lammertsma

Reputation: 38252

You can simply use setCurrentItem() to navigate to the last page in the ViewPager when it's attached to the View.

Upvotes: 3

Praful Bhatnagar
Praful Bhatnagar

Reputation: 7435

why don't you reverse the list of you view in view pager and use setCurrentItem(int) or setCurrentItem(int,boolean) and set the last one at the launch of the activity/fragment..

Upvotes: 8

Related Questions