I am trying to put a ViewPager
with different fragments with different heights. I know that wrap_content
is not working with ViewPager
so I am trying to set pager height dinamically.
I am setting the pager height in a page listener:
...
indicator.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int selected) {
final View view = fragments[selected].getView();
if (view != null) {
pager.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, view
.getMeasuredHeight()));
}
}
Unfortunately it is not working because the value returned by getMeasuredHeight()
on Fragment
is wrong. What am I doing wrong?
This is my solution:
ViewTreeObserver viewTreeObserver = mViewPager.getViewTreeObserver();
viewTreeObserver
.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
int viewPagerWidth = mViewPager.getWidth();
float viewPagerHeight = (float) (viewPagerWidth * FEATURED_IMAGE_RATIO);
layoutParams.width = viewPagerWidth;
layoutParams.height = (int) viewPagerHeight;
mViewPager.setLayoutParams(layoutParams);
mViewPager.getViewTreeObserver()
.removeGlobalOnLayoutListener(this);
}
});
I call it in onResume();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With