Reputation: 669
I m trying to set view pager height to wrap_content using this Android: I am unable to have ViewPager WRAP_CONTENT
But it's leaving extra white space at the bottom
How do I remove this space?
This is my xml code:
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
card_view:cardCornerRadius="@dimen/card_corner_radius">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.test.android.custom_views.WrapContentHeightViewPager
android:id="@+id/similarRecipesPager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:visibility="visible" />
</LinearLayout>
</android.support.v7.widget.CardView>
Upvotes: 2
Views: 5375
Reputation: 6622
Try This, Overriding onMeasure of your ViewPager
as follows will make it get the height of the biggest child it currently has.
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int height = 0;
for(int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int h = child.getMeasuredHeight();
if(h > height) height = h;
}
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
Upvotes: 2
Reputation: 3776
If you use WRAP_CONTENT to define your height, and the content is not big enough you will have extra space, because that is the intended behaviour.
If I had understood you correctly, you want your ViewPager to occupy all the possible space of your activity / fragment where other views are in play as well.
If you want a ViewPager that takes all the space available, you should use the weight
property of your LinearLayout
:
<LinearLayout android:orientation="vertical"
android:layout_height="match_parent"
android:layout_width="match_parent">
<ViewPager android:id="@+id/my_view_pager"
android:layout_height="0dp"
android:layout_width="match_parent"
android:layout_weight="1"/>
<View
android:id="@+id/other_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
This way no matter the content of your viewPager, it will fill all the extra white space.
Upvotes: 0