Source link: https://gist.github.com/AlexBlokh/1bc4878882ff777f2836
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"/>