繁体   English   中英

RecyclerView 在布局中不显示任何项目

[英]RecyclerView does not display any items when it is in a layout

我有一个导航抽屉活动,其中包含一个包含 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM