直接访问正常的RecyclerView被include后显示为空的问题求助
RecyclerView通过include引入后无条目显示问题
直接访问包含RecyclerView的视图时,所有条目正常显示;但将该视图通过<include>标签引入到父视图后,RecyclerView可见(能看到背景色)但无任何条目。
相关代码
RecyclerView所在布局(list_fragment.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" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/list_items" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/purple_200" app:layoutManager="LinearLayoutManager" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
父视图布局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center" tools:context=".MainActivity"> <include layout="@layout/list_fragment" /> <include layout="@layout/controls_fragment" /> </LinearLayout>
ListFragment的初始化代码
val context = requireContext() binding.listItems.layoutManager = LinearLayoutManager(context) val listItemAdapter = ListItemAdapter(context, items) binding.listItems.adapter = listItemAdapter
问题原因及解决方案
核心原因
你大概率同时执行了两种布局加载逻辑:在Activity布局里通过<include>引入list_fragment.xml,又在Activity中通过FragmentManager加载了ListFragment。这会导致界面上存在两个RecyclerView:
- 一个是
<include>引入的未初始化实例(仅显示背景,无适配器和数据) - 另一个是ListFragment加载的已初始化实例(有数据,但可能被前者覆盖或未正确显示)
解决方案
二选一即可:
- 移除Activity布局中的
<include>标签:仅通过FragmentManager加载ListFragment,保持原Fragment的初始化逻辑不变。 - 移除Fragment的加载逻辑:直接在Activity中初始化
<include>引入的RecyclerView,示例代码如下:// Activity中初始化代码 val binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) val listItems = binding.listItems listItems.layoutManager = LinearLayoutManager(this) val adapter = ListItemAdapter(this, items) listItems.adapter = adapter
额外注意点
如果选择保留<include>方式:
- 若
<include>标签指定了android:id,需在代码中使用该id查找RecyclerView - 父布局的
android:gravity="center"若无需子View居中,可移除该属性避免潜在布局冲突
内容的提问来源于stack exchange,提问作者Michael
相关产品推荐
相关产品推荐

