Reputation: 740
I am using 3 ViewPagers
on a single LinearLayout
. and i want to set the height of ViewPager
to wrap_content
dynamically.
My fragment is loaded in ViewPager
dynamically also. So on page change if the fragment's height is more than the viewpager's height then the viewpager's height should be automatically increased.
Layout is like
Please suggest what to do?
Upvotes: 2
Views: 4806
Reputation: 2321
The problem is that the "wrap_content" doesn't seem to be working with the View pager. Here is the solution:
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;
public class CustomViewPager extends ViewPager {
public CustomViewPager(Context context) {
super(context);
}
public CustomViewPager(Context context, AttributeSet attrs){
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, 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);
}
}
reference: Android: I am unable to have ViewPager WRAP_CONTENT
Upvotes: 5
Reputation: 3028
Assuming the implementation looks as follows,
<LinearLayout android:orientation="vertical">
<ViewPager />
<ViewPager />
<ViewPager />
</LinearLayout>
then setting the height of the ViewPagers to wrap_content
should have the desired result. There is no need to do this dynamically. Otherwise, if you really want/need to do it dynamically, just set the ViewPager layoutParams to the following from code:
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
viewPager.setLayoutParams(lp);
The parameters in the LayoutParams constructor are (width, height), and you need to change the width if you don't want that to be wrap_content.
Upvotes: 0