RecyclerView 的 LayoutManager 可以根据项目的宽度自动设置列数。

6
我正在尝试构建一个涉及RecyclerView或GridView的UI,其中我希望根据我动态填充的项的数量和宽度自动设置列数。
以下是我迄今为止实现的图像...

my current UI

这是我想要实现的图像...

my target UI

我的项目布局 xml

<TextView
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:background="@drawable/hollow_white_background"
        android:id="@+id/foodItemName"
        android:text="PIZZA"
        android:gravity="center"
        android:textColor="@color/colorGray300"
        android:textStyle="bold"
        android:textSize="15sp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp" />

请帮忙!

请提供项目布局的XML和您用于配置GridLayoutManager的代码。 - andrea.petreri
看了一下你的目标UI,我认为你不能使用标准布局管理器来使用RecyclerView实现它。你需要一种类似FlowLayout的布局方式。有许多实现可用。例如这里是我的一个存储库,其中包括类似的内容。 - andrea.petreri
也许 FlowLayout 是你正在寻找的。请参阅 https://github.com/ApmeM/android-flowlayout 或 https://github.com/blazsolar/FlowLayout。 - Eugen Pechanec
2个回答

0
在您的xml文件中,为GridView添加android:numColumns="auto_fit"和android:stretchmode="columnWidth"属性。第一个属性根据屏幕大小决定应该有多少列,第二个属性决定如何处理剩余的额外空间,在这种情况下增加列宽度。

1
我已经完成了这个任务,但是它仍然只显示两列,并且我的项目靠左对齐,无法处理额外的空间。我想要的是当我的项目宽度较小时,应该显示3列或更多,当宽度较大时,应该自动显示1或2列! - Ayush Maurya
@AyushMaurya 好的,那些属性应该正好符合您的需求。您能否更新问题并提供您当前的XML文件? - Onur Çevik
<GridView android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@+id/guideText" android:layout_marginTop="10dp" android:numColumns="auto_fit" android:horizontalSpacing="10dp" android:verticalSpacing="10dp" android:stretchMode="columnWidth" android:gravity="center" android:id="@+id/foodItemGridList"></GridView> 这是我使用的XML,问题仍然相同。 - Ayush Maurya
我认为问题出在你设置了特定的按钮(或TextView,无论它们是什么)宽度上。尝试将每个按钮的宽度设置为“wrap_content”。 - Onur Çevik
不,它只是“wrap_content”。 - Ayush Maurya
显示剩余2条评论

0

尝试使用StaggeredGridLayoutManager作为RecyclerView的LayoutManager,并将item_layout.xmlwidth固定。


StaggeredGridLayoutManager 影响的是行,而不是列! - Ayush Maurya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接