我有一个ViewPager包含3个片段,问题是每个片段有不同的高度。在ViewPager中,我尝试使用wrap_content的高度,但它不工作。
编辑
我需要做的是有ViewPager调整大小时,我通过片段切换。
你知道吗?
您需要在视图页中设置高度,而不是xml。
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);
}
}
玩弄onMeasure方法会得到你想要的,Viewpager正在控制其子元素的高度和宽度
如果这不起作用,你可以覆盖viewpager的getPageHeight和GetPagewidth方法
@Override
public float getPageHeight(int position) {
//Return different height based on position.
// Height is returned as a float
if(position == 1)
{
return (0.35f);
}
else{
retrun 0.50f;
}
}
通过告诉ViewPager
到wrap_content
,它的高度将是片段中最大的。然后,如果你有比最高的片段短的其他片段,它们将在ViewPager
内显得更短。ViewPager
同时持有所有三个碎片-它不移除碎片一个到左边和右边,因为他们需要准备好移动。
因此ViewPager
的高度总是最高的Fragment的高度。相反,您可以将所有片段的高度设置为match_parent
,并将ViewPager
的大小设置为其父级(使用match_parent
)或尝试使用wrap_content
将其适合于最大片段的高度(虽然我不知道使用wrap_content
和match_parent
时如何工作)