带有不同项目高度的水平RecyclerView(带有SnapHelper)

时间:2020-01-09 13:34:23

标签: android android-recyclerview height

我具有以下结构(XML):

<androidx.core.widget.NestedScrollView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:clickable="true"
    android:focusable="true"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="@drawable/bottom_style"
    android:scrollIndicators="none"
    app:behavior_hideable="false"
    app:behavior_peekHeight="@dimen/peek_height"
    app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:paddingStart="18dp"
        android:paddingTop="6dp"
        android:paddingEnd="18dp"
        android:paddingBottom="6dp">

        <androidx.recyclerview.widget.RecyclerView
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            android:layout_marginTop="20dp"/>
    </LinearLayout>
</androidx.core.widget.NestedScrollView>

因此,我安装了适配器并配置了RecyclerView:

recyclerView.setAdapter(new MyRecyclerAdapter(context, myList));
recyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
recyclerView.setNestedScrollingEnabled(false);

/**Creates a ViewPager-like behavior**/
SnapHelper snapHelper = new PagerSnapHelper();
snapHelper.attachToRecyclerView(recyclerView);

MyRecyclerAdapter 中,为每个 RecyclerView 项目动态填充视图,并且每个项目的高度都不同。

问题在于, RecyclerView 的总体高度由第一项确定,所有后续高度大于此高度的项在以下阶段均被裁剪(我什至可以说缩小)。他们的创造。

这是它的样子:

enter image description here

enter image description here

enter image description here


如何解决?


已解决:

我添加了代码,用于动态填充项目 View 后计算并设置新大小( viewHolder.parent 它是 recyclerView ):

int newHeight = 0;
View itemView = viewHolder.itemView;
itemView.measure(
    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
newHeight += itemView.getMeasuredHeight();
newHeight += DpToPx(8+15);
newHeight += 1;
LinearLayout.LayoutParams llParams = (LinearLayout.LayoutParams) viewHolder.parent.getLayoutParams();
llParams.height = newHeight;
viewHolder.parent.setLayoutParams(llParams);

在此处了解更多信息:https://stackoverflow.com

0 个答案:

没有答案