[英]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.