Skip to content

Instantly share code, notes, and snippets.

@fdoyle
Last active August 22, 2022 11:02
Show Gist options
  • Save fdoyle/233a7703077dbdcedca8 to your computer and use it in GitHub Desktop.
Save fdoyle/233a7703077dbdcedca8 to your computer and use it in GitHub Desktop.
PageTransform + padding on viewpager doesn't work. this fixes it
package com.foo.ui.view;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;
/**
* Created by fdoyle on 11/2/15.
*/
public class FixedTransformerViewPager extends ViewPager {
PageTransformer pageTransformer;
public FixedTransformerViewPager(Context context) {
super(context);
}
public FixedTransformerViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void setPageTransformer(boolean reverseDrawingOrder, ViewPager.PageTransformer transformer) {
this.pageTransformer = transformer;
}
@Override
protected void onPageScrolled(int position, float offset, int offsetPixels) {
super.onPageScrolled(position, offset, offsetPixels);
fixedPageScrolled(position, offset, offsetPixels);
}
protected void fixedPageScrolled(int position, float offset, int offsetPixels) {
int clientWidth = getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
if (pageTransformer != null) {
final int scrollX = getScrollX();
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
final ViewPager.LayoutParams lp = (ViewPager.LayoutParams) child.getLayoutParams();
if (lp.isDecor) continue;
//note the getPaddingLeft() that now exists
final float transformPos = (float) (child.getLeft() - getPaddingLeft() - scrollX) / clientWidth;
pageTransformer.transformPage(child, transformPos);
}
}
}
}
@samschechter
Copy link

Just thought you should know you are my hero. Great work

@rafaelneiva
Copy link

Great! Thank you for sharing!

@Zimins
Copy link

Zimins commented Jan 10, 2018

I tried to fix transformer....but was too hard.
This code is the best solution!

@esoxjem
Copy link

esoxjem commented Sep 25, 2018

@hellaandrew
Copy link

You are actually a god

@hongyangAndroid
Copy link

thx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment