ViewPager 和片段

ViewPager and Fragment

我有一个包含 3 个片段的 ViewPager,问题是每个片段都有不同的高度。在 ViewPager 中,我尝试使用 wrap_content 作为高度,但它不起作用。

编辑

我需要做的是在切换片段时让 ViewPager 调整大小。

有什么想法吗?

通过告诉 ViewPagerwrap_content 它的高度将是最大的片段。然后,如果您有其他片段比最高片段短,它们将在 ViewPager 内显得更短。 ViewPager 一次包含所有三个片段 - 它不会删除左右一个片段,因为它们需要准备好移动。

因此 ViewPager's height is always that of the tallest Fragment. Instead, you could set all the fragments' 的高度变为 match_parent 并且 ViewPager 变为其父级的大小(使用 match_parent)或尝试和使用 wrap_content 使其适合最大片段的高度(虽然我不知道一起使用 wrap_contentmatch_parent 时它会如何工作)

您需要在视图分页器中设置高度,而不是 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 正在控制其 children

的高度 + 宽度

如果这不起作用,您可以覆盖视图寻呼机的 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;
                  }
        }