4

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

NZJames
  • 4,963
  • 15
  • 50
  • 100

2 Answers2

5

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

Community
  • 1
  • 1
Marius
  • 810
  • 7
  • 20
  • So this would be the best practice way to achieve this? There is no built in way to do it without manually setting heights? – NZJames Jul 10 '14 at 13:48
1

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"/>
FireZenk
  • 1,056
  • 1
  • 16
  • 28