Skip to content

Instantly share code, notes, and snippets.

@lesterlopez-dev
Created August 28, 2018 02:44
Show Gist options
  • Save lesterlopez-dev/bd30e7888c92173ed0d6507f1805e252 to your computer and use it in GitHub Desktop.
Save lesterlopez-dev/bd30e7888c92173ed0d6507f1805e252 to your computer and use it in GitHub Desktop.
PercentViewPager is an extension for ViewPager that can control W & H by percentage.

PercentViewPager

To add it on xml

<PercentViewPager
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:pvp_percentHeight="50"
    app:pvp_percentWidth="50"/>
public class PercentViewPager extends ViewPager {
private int WIDTH_PERCENT = Integer.MIN_VALUE;
private int HEIGHT_PERCENT = Integer.MIN_VALUE;
public PercentViewPager(@NonNull Context context) {
super(context);
init(context, null);
}
public PercentViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
if (attrs == null) return;
TypedArray a = context.getTheme().obtainStyledAttributes(attrs,
R.styleable.PercentViewPager, 0, 0);
try {
//get the text and colors specified using the names in attrs.xml
WIDTH_PERCENT = a.getInteger(R.styleable.PercentViewPager_pvp_percentWidth, Integer.MIN_VALUE);
HEIGHT_PERCENT = a.getInteger(R.styleable.PercentViewPager_pvp_percentHeight, Integer.MIN_VALUE);
} finally {
a.recycle();
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
ViewGroup.LayoutParams viewParams = getLayoutParams();
DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
int height = (int) (metrics.heightPixels * (HEIGHT_PERCENT / 100f));
int width = (int) (metrics.widthPixels * (WIDTH_PERCENT / 100f));
if (HEIGHT_PERCENT != Integer.MIN_VALUE)
viewParams.height = height;
if (WIDTH_PERCENT != Integer.MIN_VALUE)
viewParams.width = width;
setLayoutParams(viewParams);
}
}
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="PercentViewPager">
<attr name="pvp_percentHeight" format="integer" />
<attr name="pvp_percentWidth" format="integer" />
</declare-styleable>
</resources>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment