ViewPager wrap_content 无效原理分析,解决方案

现象

ViewPager 在设置高度为 android:layout_height=“wrap_content” 时并没有使用子view的高度,反而像是适应父view的高度,代码如下。
布局文件:

<androidx.viewpager.widget.ViewPager
   android:id="@+id/vp_wrapContentVp_1"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:background="@color/skx_ffdee9" />
<!--注:为了方便识别ViewPager的范围,添加了一个浅色的背景-->

adapter 布局:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="100dp">

   <ImageView
       android:id="@+id/iv_wrapContentVp_image"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:scaleType="center"
       tools:ignore="ContentDescription" />

</FrameLayout>

效果:
image.png

原理分析

既然ViewPager 的高度设置为 wrap_content 时无效,那么首先查看下onMeasure 方法中有没有做特殊处理。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    // For simple implementation, our internal size is always 0.
    // We depend on the container to specify the layout size of
    // our view.  We can't really know what it is since we will be
    // adding and removing different arbitrary views and do not
    // want the layout to change as this happens.
    // 设置测量大小为默认的大小
    setMeasuredDimension(getDefaultSize(0, widthMeasureSpec),
            getDefaultSize(0, heightMeasureSpec));

    final int measuredWidth = getMeasuredWidth();
    final int maxGutterSize = measuredWidth / 10;
    mGutterSize = Math.min(maxGutterSize, mDefaultGutterSize);

    // 设置child的宽高,大小为ViewPager的测量大小减去其内边距
    int childWidthSize = measuredWidth - getPaddingLeft() - getPaddingRight();
    int childHeightSize = getMeasuredHeight() - getPaddingTop() - getPaddingBottom();

    // ---忽略Decor views 的测量---
    
    // 设置child view的 MeasureSpec
    mChildWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize, MeasureSpec.EXACTLY);
    mChildHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeightSize, MeasureSpec.EXACTLY);

    // ---忽略其他代码

    // Page views next.
    size = getChildCount();
    for (int i = 0; i < size; ++i) {
        final View child = getChildAt(i);
        if (child.getVisibility() != GONE) {
            // ---忽略其他代码
             
            final LayoutParams lp = (LayoutParams) child.getLayoutParams();
            if (lp == null || !lp.isDecor) {
                final int widthSpec = MeasureSpec.makeMeasureSpec(
                        (int) (childWidthSize * lp.widthFactor), MeasureSpec.EXACTLY);
                // 测量child 的大小
                child.measure(widthSpec, mChildHeightMeasureSpec);
            }
        }
    }
}

ViewPager 在onMeasure(int widthMeasureSpec, int heightMeasureSpec) 方法一开始就对宽高进行了默认设置,在此之前并没有进行child view 的测量,故而当高度设置为"wrap_content"时不会去匹配child view 的高度。

在测量完自己之后,取得测量的宽高减去内边距后,设置为 child view 的宽高,而后再生成MeasureSpec,并以此来对child view进行测量。这也就解释了为什么明明设置了child view 的宽高,但是并不生效,反而去匹配父布局的大小。

解决方案

public class WrapContentHeightViewPager extends ViewPager {
   
   public WrapContentHeightViewPager(@NonNull Context context) {
       super(context);
   }

   public WrapContentHeightViewPager(@NonNull Context context, @Nullable 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);
   }
}

此上来自网络上大多的解决方案,那么到底对不对呢?效果如下:
image.png

可以看出,虽然调整了高度,但是仍没有达到我们预期的目标,我们在 adapter 的布局中指定了高度是100dp,所以说 上面的答案是错误的!!!
那么问题出在哪里呢?我们看下上面代码的

child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));

这一行,高度的MeasureSpec 指定大小是0,mode为 MeasureSpec.UNSPECIFIED。我们知道一个view 的大小受自身的LayoutParams 和父view 的MeasureSpec 的双重限制,查看下ViewGroup 中对child 的测量

/**
* Ask one of the children of this view to measure itself, taking into
* account both the MeasureSpec requirements for this view and its padding.
* The heavy lifting is done in getChildMeasureSpec.
*
* @param child The child to measure
* @param parentWidthMeasureSpec The width requirements for this view
* @param parentHeightMeasureSpec The height requirements for this view
*/
protected void measureChild(View child, int parentWidthMeasureSpec,
       int parentHeightMeasureSpec) {
   // child 自身的LayoutParams
   final LayoutParams lp = child.getLayoutParams();
   // 获取child view 正确的MeasureSpec
   final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
           mPaddingLeft + mPaddingRight, lp.width);
   final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
           mPaddingTop + mPaddingBottom, lp.height);

   child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}

而上面的代码中缺少了child 的LayoutParams配置,修改如下:

// child 的大小受自身的LayoutParams 和父view 的MeasureSpec 的双重限制!测量高度需要同时考虑这两个因素。
ViewGroup.LayoutParams lp = child.getLayoutParams();
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(lp.height, heightMeasureSpec));

再次看下效果:
image.png

LayoutInflater#inflate 指定root view

如果显示不对的话,检查 PagerAdapter#instantiateItem 中关于item 的初始化,要使用指定root 的重载方法,即 android.view.LayoutInflater#inflate(int, android.view.ViewGroup, boolean)。正如上面所说,child view 的大小受自身的LayoutParams 和 parent view 的MeasureSpec 双重制约。
示例:

       @NotNull
       @Override
       public Object instantiateItem(@NotNull ViewGroup container, int position) {
           View view = LayoutInflater.from(container.getContext()).inflate(R.layout.adapter_view_pager_wrap_content, container, false);
           // 注意:不要使用未指定root 的重载方法
           // View view = LayoutInflater.from(container.getContext()).inflate(R.layout.adapter_view_pager_wrap_content, null);
           ImageView imageView = view.findViewById(R.id.iv_wrapContentVp_image);
           imageView.setImageResource(mDataList.get(position));
           container.addView(view);
           return view;
       }

扩展

  • 其他的view把高度设置成 wrap_content 是否同样存在无效的情况,比如ListVew、RecyclerView、GridView…?是否是相同的原因?
  • android.view.LayoutInflater#inflate(int, android.view.ViewGroup, boolean) 和 android.view.LayoutInflater#inflate(org.xmlpull.v1.XmlPullParser, android.view.ViewGroup, boolean) 的区别是什么?
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,490评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,581评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,830评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,957评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,974评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,754评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,464评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,357评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,847评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,995评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,137评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,819评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,482评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,023评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,149评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,409评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,086评论 2 355

推荐阅读更多精彩内容