I have a navigation drawer activity that contains a fragment that contains a RecyclerView. This RecyclerView works perfectly if it is the only component in this fragment, but I want to add a button above the RecyclerView and therefore insert the RecyclerView and the button in a LinearLayout. But then the RecyclerView has disappeared or no longer shows any elements.
How can I embed this RecyclerView in a layout?
RecyclerView works with this one:
<?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 has disappeared in this one:
<?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>
See complete project here: https://github.com/jriegraf/MyApp
You have this code in 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));
}
This is your problem. Once you wrap RecyclerView
into LinearLayout
, this
if (view instanceof RecyclerView)
isn't true any more, because now, view
's type is LinearLayout
.
If the view doesn't remove the recyclerView, you can ommit the if
statement, and change this line:
RecyclerView recyclerView = (RecyclerView) view;
into:
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.list);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.