RecyclerView的Item没有填充屏幕原因分析

在项目中使用RecyclerView实现类似QQ的左滑菜单列表时,遇到每个Item只占半个屏幕的问题。检查发现SwipeLayout逻辑无误,ViewHolder创建正常。问题根源在于 Framelayout 中的子视图 ConstraintLayout,即使设置为match_parent,也可能因子视图尺寸小导致FrameLayout缩小。解决方案是在ConstraintLayout中添加min_width属性,设置较大像素值,如1000dp,以确保Item填充屏幕。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  项目需求是这样的:使用RecyclerView实现一个列表,列表中每个Item可以左滑出现菜单,类似QQ。
  实现过程首先需要自定义一个组件,即每个Item的根布局组件。这个组件是继承自FrameLayout,所以组件的特性和FrameLayout差不多,就是子视图相当于放在栈中,最新放置的视图会遮挡旧视图。
  这个控件实现完毕后,然后编写list_item布局文件,以这个控件为根布局,第一个菜单视图使用LinearLayout,第二个主视图使用了Android后来推出的ConstraintLayout,布局文件内容如下

<?xml version="1.0" encoding="utf-8"?>
<cn.anonymous.widget.SwipeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/member_item_height"
    android:id="@+id/swipe_layout">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/delete"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="@string/iml_back_delete"
            android:textSize="@dimen/text_size_16"
            android:textColor="@color/colorWhite"
            android:background="@color/colorRed"
            android:gravity="center"
            android:paddingLeft="@dimen/text_delete_padding"
            android:paddingStart="@dimen/text_delete_padding"
            android:paddingEnd="@dimen/text_delete_padding"
            android:paddingRight="@dimen/text_delete_padding"/>
    </LinearLayout>

    <android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:minWidth="0dp"
        android:background="@color/colorGreen"
        android:id="@+id/front_layout">

        <cn.anonymous.circleimageview.CircleImageView
            android:id="@+id/member_avatar"
            android:layout_width="@dimen/circle_image_size"
            android:layout_height="@dimen/circle_image_size"
            android:src="@mipmap/iv_default_avatar"
            android:scaleType="fitCenter"
            app:civ_border_width="1dip"
            app:civ_border_color="@color/colorImageBorder"
            app:civ_oval="true"
            android:layout_margin="@dimen/activity_horizontal_margin"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"/>

        <TextView
            android:id="@+id/text_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/text_default"
            android:textSize="@dimen/text_size_16"
            android:textColor="@color/colorBlack"
            android:layout_marginLeft="@dimen/activity_horizontal_margin"
            android:layout_marginTop="@dimen/space_margin"
            app:layout_constraintLeft_toRightOf="@id/member_avatar"
            app:layout_constraintTop_toTopOf="@id/member_avatar"/>

        <TextView
            android:id="@+id/text_last_in"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/iml_last_in"
            android:textSize="@dimen/text_size_12"
            android:layout_marginLeft="@dimen/activity_horizontal_margin"
            android:layout_marginTop="@dimen/space_margin"
            app:layout_constraintLeft_toRightOf="@id/member_avatar"
            app:layout_constraintTop_toBottomOf="@id/text_name"/>

        <TextView
            android:id="@+id/text_in_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/text_default_datetime"
            android:textSize="@dimen/text_size_12"
            android:layout_marginLeft="@dimen/tab_margin"
            android:layout_marginTop="@dimen/space_margin"
            app:layout_constraintLeft_toRightOf="@id/text_last_in"
            app:layout_constraintTop_toBottomOf="@id/text_name"/>

        <TextView
            android:id="@+id/text_last_out"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/iml_last_out"
            android:textSize="@dimen/text_size_12"
            android:layout_marginLeft="@dimen/activity_horizontal_margin"
            android:layout_marginBottom="@dimen/space_margin"
            app:layout_constraintLeft_toRightOf="@id/member_avatar"
            app:layout_constraintBottom_toBottomOf="@id/member_avatar"/>

        <TextView
            android:id="@+id/text_out_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/text_default_datetime"
            android:textSize="@dimen/text_size_12"
            android:layout_marginLeft="@dimen/tab_margin"
            android:layout_marginBottom="@dimen/space_margin"
            app:layout_constraintLeft_toRightOf="@id/text_last_out"
            app:layout_constraintBottom_toBottomOf="@id/member_avatar"/>
    </android.support.constraint.ConstraintLayout>

</cn.anonymous.widget.SwipeLayout>

  根据布局代码来看应该是没有问题,预计实现的效果就是像QQ消息列表那样。但是运行后发现每个Item只占了半个屏幕,但是滑动效果还是正常的,说明SwipeLayout这个自定义控件逻辑没有问题。

  然后在网上搜索到的大多原因是创建ViewHolder时没有传入parent参数,所以检查了下,代码如下

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_member_list, parent, false);
        return new ViewHolder(view);
    }

  这些都没有问题,昨天看FrameLayout源代码的时候,想起那个onMeasure函数的测量方法

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int count = getChildCount();

    // MeasureSpec.EXACTLY表示在布局代码中指定了精确的像素值
    // 所以这个代码如果Framelayout指定了match_parent属性,那么布尔值可能就是true了
        final boolean measureMatchParentChildren =
                MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY ||
                MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;
        mMatchParentChildren.clear();

        int maxHeight = 0;
        int maxWidth = 0;
        int childState = 0;

    // 遍历FrameLayout中子视图,并测量子视图大小,然后记录子视图中最大高度,最大宽度
        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (mMeasureAllChildren || child.getVisibility() != GONE) {
                measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
                final LayoutParams lp = (LayoutParams) child.getLayoutParams();
                // 子视图的实际测量值
                maxWidth = Math.max(maxWidth,
                        child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
                maxHeight = Math.max(maxHeight,
                        child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);
                childState = combineMeasuredStates(childState, child.getMeasuredState());
                // 如果子视图设置了match_parent属性,那么先加到列表中
                if (measureMatchParentChildren) {
                    if (lp.width == LayoutParams.MATCH_PARENT ||
                            lp.height == LayoutParams.MATCH_PARENT) {
                        mMatchParentChildren.add(child);
                    }
                }
            }
        }

        // Account for padding too
        maxWidth += getPaddingLeftWithForeground() + getPaddingRightWithForeground();
        maxHeight += getPaddingTopWithForeground() + getPaddingBottomWithForeground();

        // Check against our minimum height and width
        maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
        maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());

        // Check against our foreground's minimum height and width
        final Drawable drawable = getForeground();
        if (drawable != null) {
            maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
            maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
        }

    // 根据前边步骤获取的maxHeight、maxWidth值更新FrameLayout的像素大小
        setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
                resolveSizeAndState(maxHeight, heightMeasureSpec,
                        childState << MEASURED_HEIGHT_STATE_SHIFT));

        // 处理刚才添加到列表中的子视图
        count = mMatchParentChildren.size();
        if (count > 1) {
            for (int i = 0; i < count; i++) {
                final View child = mMatchParentChildren.get(i);
                final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

                final int childWidthMeasureSpec;
                // 如果子视图有match_parent属性,那么计算子视图实际应有的宽度
                if (lp.width == LayoutParams.MATCH_PARENT) {
                    final int width = Math.max(0, getMeasuredWidth()
                            - getPaddingLeftWithForeground() - getPaddingRightWithForeground()
                            - lp.leftMargin - lp.rightMargin);
                    childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
                            width, MeasureSpec.EXACTLY);
                } else {
                    childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
                            getPaddingLeftWithForeground() + getPaddingRightWithForeground() +
                            lp.leftMargin + lp.rightMargin,
                            lp.width);
                }

        ...
        ...
        ...

                child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
            }
        }
}

  通过FrameLayout的OnMeasure函数大致可以发现,即使你FrameLayout设置了match_parent,如果子视图很小,那么FrameLayout也会相应调小,然后更新设置了match_parent的子视图的大小。所以这个问题应该出现在ConstraintLayout,因为如果ConstraintLayout的测量值可以为match_parent的话,那么FrameLayout肯定也是match_parent占满屏幕。下面来看看ConstraintLayout的onMeasure函数。通过查看源码发现,这种情况下对ConstraintLayout设置match_parent属性是没用的。

最后的解决办法是添加min_width属性值,给一个比较大的像素值,比如1000dp

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值