I have setup a simple ViewPager that has an ImageView with a height of 200dp on each page.
Here is my pager:
pager = new ViewPager(this);
pager.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
pager.setBackgroundColor(Color.WHITE);
pager.setOnPageChangeListener(listener);
layout.addView(pager);
Despite the height set as wrap_content, the pager always fills the screen even though the imageview is only 200dp. I tried to replace the height of the pager with "200" but that gives me different results with multiple resolutions. I am unable to add "dp" to that value. How do I add 200dp to the pager's layout?
I was just answering a very similar question about this, and happened to find this when looking for a link to back up my claims, so lucky you :)
My other answer:
The ViewPager does not support
wrap_content
as it (usually) never have all its children loaded at the same time, and can therefore not get an appropriate size (the option would be to have a pager that changes size every time you have switched page).You can however set a precise dimension (e.g. 150dp) and
match_parent
works as well.You can also modify the dimensions dynamically from your code by changing the
height
-attribute in itsLayoutParams
.For your needs you can create the ViewPager in its own xml-file, with the layout_height set to 200dp, and then in your code, rather than creating a new ViewPager from scratch, you can inflate that xml-file:
If the
ViewPager
you're using is a child of aScrollView
AND has aPagerTitleStrip
child you'll need to use a slight modification of the great answers already provided. For reference my XML looks like this:In your
onMeasure
you have to ADD the measuredHeight of thePagerTitleStrip
if one is found. Otherwise its height won't be considered into the largest height of all the children even though it takes up additional space.Hope this helps someone else. Sorry that it's a bit of a hack...
I based my answer on Daniel López Lacalle and this post http://www.henning.ms/2013/09/09/viewpager-that-simply-dont-measure-up/. The problem with Daniel's answer is that in some cases my children had a height of zero. The solution was to unfortunately measure twice.
This also lets you set a height on the ViewPager if you so want to or just wrap_content.
I just bumped into the same issue. I had a ViewPager and I wanted to display an ad at the button of it. The solution I found was to get the pager into a RelativeView and set it's layout_above to the view id i want to see below it. that worked for me.
here is my layout XML:
in my case adding
clipToPadding
solved the problem.Cheers!
When using static content inside the viewpager and you wish no fancy animation you may use the following view pager