RatioViewPager

Additional

Language
XML
Version
N/A
Created
Dec 23, 2014
Updated
Mar 31, 2017 (Retired)
Owner
Aleksandr Blokh (AlexBlokh)
Activity
N/A
Badge
Generate
Download
Source code

Advertising

ViewPager with custom aspect ratio

Java file (969 bytes): RatioViewPager.java

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));
    }
}

XML file (154 bytes): attrs.xml

<resources>
  <attr name="ratio" format="float"/>
  <declare-styleable name="RatioViewPager">
    <attr name="ratio"/>
  </declare-styleable>
</resources>

XML file (208 bytes): layout.xml

<com.package.RatioViewPager
            android:id="@+id/shop_item_cover_pager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:ratio="0.75"/>