Last active
March 31, 2017 11:36
-
-
Save AlexBlokh/1bc4878882ff777f2836 to your computer and use it in GitHub Desktop.
ViewPager with custom aspect ratio
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<resources> | |
<attr name="ratio" format="float"/> | |
<declare-styleable name="RatioViewPager"> | |
<attr name="ratio"/> | |
</declare-styleable> | |
</resources> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<com.package.RatioViewPager | |
android:id="@+id/shop_item_cover_pager" | |
android:layout_width="match_parent" | |
android:layout_height="wrap_content" | |
app:ratio="0.75"/> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
} |
Try adding this:
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
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
I have the same problem as @andazlan has. Somebody fixed it?