在使用ViewPager
的時候由於高度是自適應的,所以高度使用了wrap_content
,但是一直顯示不了,最後發現不能使用wrap_content
。在網上找了之後自定義ViewPager可解決。代碼如下:
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;
//下面遍歷所有child的高度
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) //採用最大的view的高度。
height = h;
}
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
終於可以顯示了,But 無意中發現,使用這個第一次安裝app進入的時候還是不能顯示,研究發現第一次的時候getChildCount()
爲 0 。經過查找資料,最後驗證下面的方法可以正常使用。代碼如下:
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) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int height = 0;
//下面遍歷所有child的高度
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
child.measure(widthMeasureSpec,
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int h = child.getMeasuredHeight();
//採用最大的view的高度。
if (h > height) {
height = h;
}
}
setMeasuredDimension(getMeasuredWidth(), height);
}
}