Home » Android » android – ViewPager: set a different padding for first and last page

android – ViewPager: set a different padding for first and last page

Posted by: admin June 15, 2020 Leave a comment

Questions:

I already implemented a “page peek” feature for my ViewPager:

mPager.setClipToPadding(false);
mPager.setPadding(120, 0, 120, 0);
mPager.setPageMargin(60);

Doing this I am able to view a portion of the previous and next page. But first and last page show a bigger white space because there’s no other page in this direction to show.

How can I set a different padding for the first and last page?

How to&Answers:

I had to solve the same problem and I solved it by setting custom PageTransformer. I practically traslate the pages when at first and last position. Let me know if this works for you.

mPager.setClipToPadding(false);
mPager.setPadding(120, 0, 120, 0);
mPager.setPageMargin(60);    
mPager.setPageTransformer(false, new ViewPager.PageTransformer() {
        @Override public void transformPage(View page, float position) {
            if (mPager.getCurrentItem() == 0) {
                page.setTranslationX(-120);
            } else if (mPager.getCurrentItem() == adapter.getCount() - 1) {
                page.setTranslationX(120);
            } else {
                page.setTranslationX(0);
            }
        }
    });