在垂直 RecyclerView 中嵌套水平 RecyclerView,且动态调整大小的元素无法正确测量尺寸

问题描述 投票:0回答:1

我有一个垂直的部分列表,每个部分都有一个水平的项目列表。

嵌套列表中的每个项目宽度应与动态插入的文本相对应。

90% 的项目以适当的尺寸显示,但有些 10% 显示的宽度太大或太小,从而切断了文本。

我们如何解决这个问题?或者如何正确实现嵌套

RecyclerView

这是嵌套

RecyclerView
项目的布局文件。它使用
wrap_content
宽度作为父元素,使用
match_parent
宽度作为子元素,使宽度对应于最宽的子元素:

<androidx.cardview.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="73dp">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="29dp"
        android:singleLine="true" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="16dp"
        android:singleLine="true"
        android:layout_marginTop="36dp" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="16dp"
        android:singleLine="true"
        android:layout_marginTop="52dp" />

</androidx.cardview.widget.CardView>

这就是我初始化嵌套

RecyclerView
的方式。它是从父级(垂直)
onBindViewHolder
适配器类的
RecyclerView
调用的:

RecyclerView nestedRecyclerView = holder.view
    .findViewById(R.id.tasks_expansion)
    .findViewById(R.id.rv_expansion_tasks);
LinearLayoutManager layoutManager = new LinearLayoutManager(
    nestedRecyclerView.getContext(),
    LinearLayoutManager.HORIZONTAL,
    true
);
            

layoutManager.setInitialPrefetchItemCount(menuItem.getContentBoxes().size());
RecyclerViewAdapterContentBoxes nestedAdapter = new RecyclerViewAdapterContentBoxes(
    nestedRecyclerView.getContext(),
    menuItem.getContentBoxes()
);
nestedRecyclerView.setLayoutManager(layoutManager);
nestedRecyclerView.setAdapter(nestedAdapter);
nestedRecyclerView.setRecycledViewPool(viewPool);

我认为可能会出现问题,因为在

RecyclerView
中使用
RecylerView
,但另一方面,这似乎是应用程序中相对常见的功能。如有任何帮助,我们将不胜感激。

android android-studio android-recyclerview
1个回答
0
投票

解决方案是避免父级

wrap_content
和子级
match_parent
技巧,将宽度设置为子级的最大宽度。相反,我将父项和所有子项的宽度设置为
wrap_content
,并在同一位置添加第二个和第三个
TextView
的克隆,填充颜色与第一个
TextView
相同,但使用子项的
textSize
,并且还使文本透明(通过使
textColor
与背景相同)。在
RecyclerView
onBindViewHolder
中我添加了相应的重复文本。还将
layout_gravity
作为
center_horizontal
添加到所有三个原始
TextView
以使其居中(
gravity="center"
是不够的)。这导致在嵌套
RecyclerView
中正确测量所有视图。

© www.soinside.com 2019 - 2024. All rights reserved.