RecyclerView 挤压子项宽度

问题描述

我正在使用带有 Horizo​​ntal linearlayoutmanager 的 RecyclerView。 RecyclerView 的 child 是 CardView 尽管 child 的宽度参数仍然设置,但是 recycler view 用压缩的宽度来膨胀它

这是我的 RecyclerView

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv_popular_courses"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:listitem="@layout/card_popular_quizzes" />

这是card_popular_quizzes.xml

<androidx.cardview.widget.CardView
    android:layout_width="150dp"
    android:layout_height="wrap_content"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:minHeight="150dp"
    app:cardElevation="@dimen/card_itemcourse_elevation"
    app:cardBackgroundColor="#309C98"
    app:cardCornerRadius="16dp"
    >

<!--    app:cardElevation="10dp"-->

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_gravity="center">

        <ImageView
            android:id="@+id/quiz_thumbnail_imgvw"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:adjustViewBounds="true"
            android:cropToPadding="true"
            android:maxWidth="100dp"
            android:src="@drawable/android_developer" />

        <TextView
            android:id="@+id/quiz_textvw"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="Hall of Fame"
            android:textColor="@color/whiteTextColor"
            android:textSize="16sp"
            android:textStyle="bold"
            android:layout_marginBottom="10dp"/>

    </LinearLayout>


</androidx.cardview.widget.CardView>

此外,recyclerview 在一个片段中,这里是我添加 linearlayoutmanager代码

    public void onViewCreated(@NonNull View view,@Nullable Bundle savedInstanceState) {
        super.onViewCreated(view,savedInstanceState);
        //removed some view initialisations

        RecyclerView rvPopularCourses=view.findViewById(R.id.rv_popular_courses);
        rvPopularCourses.setLayoutManager(
                new linearlayoutmanager(view.getContext(),linearlayoutmanager.HORIZONTAL,false));
        rvPopularCourses.setAdapter(quizAdapter);
    }

这是一个视觉截图供参考

enter image description here

解决方法

LinearLayout 宽度是 wrap_content,这会导致此问题。 您必须在 card_popular_quizzes.xml

中将 LinearLayout layout_width 设置为 match_parent