界面需求需要ViewPager并自适应高度,但是设置高度的时候发现“wrap_content”没有效果。
解决方法:
自定义ViewPager,重写ViewPager的onMesure()方法:
public class RouteBusViewPager extends ViewPager {
public RouteBusViewPager(Context context) {
super(context);
}
public RouteBusViewPager(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);
}
}
网友评论