Skip to content

Instantly share code, notes, and snippets.

@putraxor
Forked from AlexBlokh/RatioViewPager.java
Created March 27, 2017 19:05
Show Gist options
  • Save putraxor/e6832645addc9d18eb27afd87f3a50db to your computer and use it in GitHub Desktop.
Save putraxor/e6832645addc9d18eb27afd87f3a50db 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));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment