NZJames
NZJames

Reputation: 5055

How to make ViewPager square sized to screen width?

I have a viewpager that I want to take up the entire width of the phone screen, however much that is. I want the height of the ViewPager to then match the width so the whole thing is square, but cannot figure out how to do this.

I have tried combinations of weight, fixed height, match_parent, wrap_content but nothing seems to achieve this

Upvotes: 4

Views: 2542

Answers (2)

FireZenk
FireZenk

Reputation: 1243

Here is another way compatible with xml and no config needed:

public class SquareViewPager extends ViewPager {

    public SquareViewPager(final Context context) {
        super(context);
    }

    public SquareViewPager(final Context context, final AttributeSet attrs) {
        super(context, attrs);
    }

    @Override protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
        final int width = getDefaultSize(getSuggestedMinimumWidth(),widthMeasureSpec);
        setMeasuredDimension(width, width);
    }

    @Override protected void onSizeChanged(final int w, final int h, final int oldw, final int oldh) {
        super.onSizeChanged(w, w, oldw, oldh);
    }
}

And then:

<my.package.SquareViewPager
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

Upvotes: 1

Marius
Marius

Reputation: 820

You can use Display to get screen size in pixels.

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = width;

Then create LayoutParams and set them to your ViewPager.

LayoutParams lp = new LayoutParams(width,height);
mViewPager.setLayoutParams(lp);

You might also want to check which value is less, width or height.

Adapted from here

Upvotes: 5

Related Questions