Android Simple RecyclerView运行后屏幕无内容显示问题求助
问题排查与修复方案
你遇到的RecyclerView不显示的问题是由3处布局配置错误导致的,逐一修改即可恢复正常:
- MainActivity布局中RecyclerView被AppBar遮挡
你使用了CoordinatorLayout作为根布局,但RecyclerView没有配置对应滚动行为,导致绘制起点和顶部的AppBarLayout重叠,内容完全被遮挡。 - 列表项根布局高度配置错误
my_row.xml的根ConstraintLayout高度设为match_parent,会让每个列表项占满整个RecyclerView的高度,即使没有被遮挡也只能看到1个条目。 - 列表项中文本重叠
CardView是FrameLayout子类,内部的两个TextView默认会叠加在左上角,第二个文本会被第一个挡住无法显示。
具体修改代码
- 修改
activity_main.xml中的RecyclerView节点,添加滚动行为:
<androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" />
- 替换整个
my_row.xml的代码,修正高度和文本布局:
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout 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:padding="8dp"> <androidx.cardview.widget.CardView android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="16dp"> <TextView android:id="@+id/myText1Id" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="18sp" android:textStyle="bold" android:text="TextView" /> <TextView android:id="@+id/myText2Id" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="4dp" android:textSize="14sp" android:text="TextView Again" /> </LinearLayout> </androidx.cardview.widget.CardView> </androidx.constraintlayout.widget.ConstraintLayout>
修改完成后重新编译运行即可正常显示列表内容。
内容的提问来源于stack exchange,提问作者marcelomo
相关产品推荐
相关产品推荐

