首页 > 解决方案 > 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

标签: javaandroidandroid-layoutandroid-recyclerview

解决方案


你有这个代码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);

推荐阅读