Skip to content

Instantly share code, notes, and snippets.

@AlexBlokh
Last active March 31, 2017 11:36
Show Gist options
  • Save AlexBlokh/1bc4878882ff777f2836 to your computer and use it in GitHub Desktop.
Save AlexBlokh/1bc4878882ff777f2836 to your computer and use it in GitHub Desktop.
ViewPager with custom aspect ratio
<resources>
<attr name="ratio" format="float"/>
<declare-styleable name="RatioViewPager">
<attr name="ratio"/>
</declare-styleable>
</resources>
<com.package.RatioViewPager
android:id="@+id/shop_item_cover_pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:ratio="0.75"/>
public class RatioViewPager extends ViewPager {
private float mRatio = 1f;
public RatioViewPager(Context context) {
super(context);
}
public RatioViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
private void init(AttributeSet attrs) {
if (attrs != null) {
TypedArray styled = getContext().obtainStyledAttributes(attrs, R.styleable.RatioViewPager);
mRatio = styled.getFloat(R.styleable.RatioViewPager_ratio, 1f);
styled.recycle();
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = (int) (width * mRatio);
setMeasuredDimension(width, height);
measureChildren(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
}
}
@andazlan
Copy link

it doesn't show at first time.... i have to touch the viewpager to show the slide... can you explain why?

@philipgiuliani
Copy link

I have the same problem as @andazlan has. Somebody fixed it?

@adiputrastwn
Copy link

Try adding this:
super.onMeasure(widthMeasureSpec, heightMeasureSpec);

@aravind12345
Copy link

aravind12345 commented Oct 25, 2016

Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
         int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = (int) (width * mRatio);
        setMeasuredDimension(width, height);
        measureChildren(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
super.onMeasure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
    }

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