Skip to content

Instantly share code, notes, and snippets.

@egslava
Created August 12, 2014 12:28
Show Gist options
  • Save egslava/589b82a6add9c816a007 to your computer and use it in GitHub Desktop.
Save egslava/589b82a6add9c816a007 to your computer and use it in GitHub Desktop.
Wrap content height ViewPager (Android)
package org.cnii.layoutloader.ui;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;
/**
* Special thanks to Daniel López Lacalle for his response
* (http://stackoverflow.com/questions/8394681/android-i-am-unable-to-have-viewpager-wrap-content/20784791#20784791)
* */
public class WrapContentHeightViewPager extends ViewPager {
public WrapContentHeightViewPager(Context context) {
super(context);
}
public WrapContentHeightViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@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);
}
}
@hiten
Copy link

hiten commented Sep 20, 2018

This is what is used. Just add a flag of fillViewPort

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fillViewport="true"
            >

          <LinearLayout
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:orientation="vertical"
              >
<android.support.design.widget.TabLayout
          android:id="@+id/tabLayout"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          />
      <android.support.v4.view.ViewPager
          android:id="@+id/case_data_view_pager"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          >
      </android.support.v4.view.ViewPager>
          </LinearLayout>
 </ScrollView>

@amrishkakadiya
Copy link

Some people are born to be awesome.!! Thank you.

@d1hamid
Copy link

d1hamid commented May 31, 2020

how i can use ? :(

@Retromantis
Copy link

Thanks, you saved me !!!

@robertocapah
Copy link

I have the same problem with @ilya-afanasev, childCount detected zero at first display, so it doesn't show until I tap the other tab. can anyone give advice?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment