美文网首页
ViewPager wrap_content 无效原理分析,解决

ViewPager wrap_content 无效原理分析,解决

作者: 沪漂意哥哥 | 来源:发表于2022-05-19 19:59 被阅读0次

    现象

    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) 的区别是什么?

    相关文章

      网友评论

          本文标题:ViewPager wrap_content 无效原理分析,解决

          本文链接:https://www.haomeiwen.com/subject/bnztprtx.html