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> |