java - RecyclerView 在布局中不显示任何项目
问题描述
我有一个导航抽屉活动,其中包含一个包含 RecyclerView 的片段。如果此 RecyclerView 是此片段中的唯一组件,则它可以完美运行,但我想在 RecyclerView 上方添加一个按钮,因此将 RecyclerView 和按钮插入到 LinearLayout 中。但随后 RecyclerView 消失或不再显示任何元素。
如何将此 RecyclerView 嵌入到布局中?
RecyclerView 适用于这个:
<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView
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:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:name="com.company.myapp.ui.ItemFragment"
app:layoutManager="LinearLayoutManager"
tools:context=".ui.home.HomeFragment"
tools:listitem="@layout/fragment_item" />
RecyclerView 在这一项中消失了:
<?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">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete Item" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:name="com.company.myapp.ui.ItemFragment"
app:layoutManager="LinearLayoutManager"
tools:context=".ui.home.HomeFragment"
tools:listitem="@layout/fragment_item" />
</LinearLayout>
在此处查看完整的项目:https ://github.com/jriegraf/MyApp
解决方案
你有这个代码HomeFragment
:
// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
recyclerView.setAdapter(new MyItemRecyclerViewAdapter(DummyContent.ITEMS, mListener));
}
这是你的问题。一旦你RecyclerView
换成LinearLayout
,这
if (view instanceof RecyclerView)
不再是真的,因为现在,view
的类型是LinearLayout
.
如果视图没有删除recyclerView,你可以省略该if
语句,并更改此行:
RecyclerView recyclerView = (RecyclerView) view;
进入:
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.list);
推荐阅读
- java - 如何在 JTable 中均匀化组件大小?
- algorithm - 如何构建路径短于给定大小的有向图?
- linkedin - 如何通过 3rd 方应用发送 Linkedin 好友请求?
- php - 在 php 中导入之前在 html 表中预览 csv
- sql - 加入 1 到多张桌子的最佳方式
- c++ - 在 SYCL 中使用障碍
- python - numpy 中的行专业和列专业是什么?
- javascript - Google 翻译 API 未翻译 HTML 标记中的某些单词
- reactjs - TypeError:无法设置未定义 App.inputChangeHandler 的属性“eName”
- python - 如何使用与 Excel 文件中的连接数据相关的值创建列