解决Viewpager设置高度为wrap_content无效的方法

今天发现设置viewpager高度为wrap_content时并没作用,stackoverflow给出了解决方案,就是自定义viewpager,重写onMesure()方法:
public class WrapContentHeightViewPager extends ViewPager {

    /**
     * Constructor
     *
     * @param context the context
     */
    public WrapContentHeightViewPager(Context context) {
        super(context);
    }

    /**
     * Constructor
     *
     * @param context the context
     * @param attrs the attribute set
     */
    public WrapContentHeightViewPager(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);
    }


}

使用的时候用WrapContentHeightViewPager代替viewpager就ok了

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,010评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,663评论 25 708
  • 《消愁》——毛不易 酒杯举起,觥筹交错,灯红酒绿的世界,你手里的那杯酒准备敬给谁? 这个暑假,火...
    好的甜甜圈阅读 466评论 0 1
  • 好几年前本要出版,几个朋友开玩笑的说到时出版了一定要给我本书啊。几年后,朋友写的小说几经周折终于出版,我也如同当年...
    本姑凉馥羽阅读 1,791评论 7 20
  • 苏华老师的《下鱼》,语言京腔京味,亲切感强,生活气息浓郁,在阅读过程中,好像是自己在经历着这个过程,映像感极强。那...
    启明星子阅读 208评论 0 0