Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@andazlan andazlan commented Aug 25, 2015

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

@philipgiuliani

This comment has been minimized.

Copy link

@philipgiuliani philipgiuliani commented Jan 11, 2016

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

@adiputrastwn

This comment has been minimized.

Copy link

@adiputrastwn adiputrastwn commented Feb 9, 2016

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

@aravind12345

This comment has been minimized.

Copy link

@aravind12345 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