如何仅用一套XML实现仅上下半部分带圆角的RecyclerView行布局?
实现方案
完全可以仅通过一套XML布局实现该效果,不需要代码动态创建布局,仅需在绑定条目数据时做少量状态切换即可。
推荐实现方式(基于Material组件,兼容性好)
1. 前置依赖
项目已引入Google Material组件库(绝大多数安卓项目默认已集成)。
2. 定义圆角样式
在res/values/styles.xml中添加3组圆角配置:
<!-- 图片仅顶部圆角样式 --> <style name="Shape.Image.TopCorner"> <item name="cornerSizeTopLeft">8dp</item> <item name="cornerSizeTopRight">8dp</item> <item name="cornerSizeBottomLeft">0dp</item> <item name="cornerSizeBottomRight">0dp</item> </style> <!-- 文本仅底部圆角样式 --> <style name="Shape.Text.BottomCorner"> <item name="cornerSizeBottomLeft">8dp</item> <item name="cornerSizeBottomRight">8dp</item> <item name="cornerSizeTopLeft">0dp</item> <item name="cornerSizeTopRight">0dp</item> </style> <!-- 文本全圆角样式(隐藏图片时使用) --> <style name="Shape.Text.AllCorner"> <item name="cornerSize">8dp</item> </style>
3. 编写单套条目XML布局
<LinearLayout 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="wrap_content" android:orientation="vertical"> <!-- 顶部图片控件 --> <com.google.android.material.imageview.ShapeableImageView android:id="@+id/iv_cover" android:layout_width="match_parent" android:layout_height="150dp" android:scaleType="centerCrop" app:shapeAppearance="@style/Shape.Image.TopCorner" android:visibility="gone"/> <!-- 底部文本控件 --> <com.google.android.material.textview.MaterialTextView android:id="@+id/tv_desc" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="16dp" android:background="#f0f0f0" app:shapeAppearance="@style/Shape.Text.BottomCorner"/> </LinearLayout>
4. 数据绑定逻辑
在RecyclerView的Adapter绑定数据时,仅需做简单状态判断:
- 若当前条目需要显示图片:将
iv_cover设为可见,同时给tv_desc设置Shape.Text.BottomCorner样式 - 若当前条目不需要显示图片:将
iv_cover设为隐藏,同时给tv_desc设置Shape.Text.AllCorner样式
无Material组件的替代方案
如果项目不使用Material组件,可以给TextView准备两个背景drawable:
- 一个是仅底部带圆角的shape
- 一个是四个角都带圆角的shape
绑定数据时直接切换TextView的background属性即可,同样只需要一套XML布局。
内容的提问来源于stack exchange,提问作者szaske
相关产品推荐
相关产品推荐

