Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Another more generic solution is to get <code>wrap_content</code> to just work.</p> <p>I've extended <code>ViewPager</code> to override <code>onMeasure()</code>. The height is wraped around the first child view. This could lead to unexpected results if the child views are not exactly the same height. For that the class can be easily extended to let's say animate to the size of the current view/page. But I didn't need that.</p> <p>You can use this ViewPager in yout XML layouts just like the original ViewPager:</p> <pre><code>&lt;view android:layout_width="match_parent" android:layout_height="wrap_content" class="de.cybergen.ui.layout.WrapContentHeightViewPager" android:id="@+id/wrapContentHeightViewPager" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true"/&gt; </code></pre> <p>Advantage: This approach allows using the ViewPager in any layout including RelativeLayout to overlay other ui elements.</p> <p>One drawback remains: If you want to use margins, you have to create two nested layouts and give the inner one the desired margins.</p> <p>Here's the code:</p> <pre><code>public class WrapContentHeightViewPager extends ViewPager { /** * Constructor * * @param context the context */ public WrapContentHeightViewPager(Context context) { super(context); } /** * Constructor * * @param context the context * @param attrs the attribute set */ public WrapContentHeightViewPager(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); // find the first child view View view = getChildAt(0); if (view != null) { // measure the first child view with the specified measure spec view.measure(widthMeasureSpec, heightMeasureSpec); } setMeasuredDimension(getMeasuredWidth(), measureHeight(heightMeasureSpec, view)); } /** * Determines the height of this view * * @param measureSpec A measureSpec packed into an int * @param view the base view with already measured height * * @return The height of the view, honoring constraints from measureSpec */ private int measureHeight(int measureSpec, View view) { int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { result = specSize; } else { // set the height from the base view if available if (view != null) { result = view.getMeasuredHeight(); } if (specMode == MeasureSpec.AT_MOST) { result = Math.min(result, specSize); } } return result; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload