In Android Studio (v.4.0.1) File -> New -> Fragment -> Fragment (List) creates a Dummy List with all components needed (Adapter, XMLs etc). When leaving the default names given by the wizard it creates these xml files :
fragment_item_list.xml :
<?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:name="de.afu.development.test.afu_portfolio_searcher_app_test.ItemFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
app:layoutManager="LinearLayoutManager"
tools:context=".ItemFragment"
tools:listitem="@layout/fragment_item" />
and fragment_item.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/item_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/text_margin"
android:textAppearance="?attr/textAppearanceListItem" />
<TextView
android:id="@+id/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/text_margin"
android:textAppearance="?attr/textAppearanceListItem" />
I can´t figure out how to inflate the Fragment in my Activity, I tried with :
getSupportFragmentManager().beginTransaction().add(R.id.list, new ItemFragment()).commit();
or
getSupportFragmentManager().beginTransaction().add(R.id.list, ItemFragment.newInstance(1)).commit();
where I know the error lies within 'R.id.list' because I get the following stacktrace error :
java.lang.IllegalArgumentException: No view found for id 0x7f....:id/list) for fragment ItemFragment ...
'R.id.list' is the ID given to the RecyclerView by the wizard.
I also tried wrapping fragment_item_list.xml and fragment_item.xml into a FrameLayout and calling R.id.blabla from within the Framelayout, I saw this in other answers, but that did not work either.
So how do I inflate that Wizard created Fragment (List) in my Activity and why does my approach not work?
you should have some ViewGroup
in your Activity
s layout, e.g. RelativeLayout
, which would be container for your Fragment
. You are setting RecyclerView
as container, this wont work as this item isn't proper container and isn't added to Activity
at all (so No view found for id
in Exception
). RecyclerView
is a part of Fragment
s layout (after creating and adding), in which you have implemented Adapter
. Will be available when Fragment
will run and you are crashing on line which tries to add Fragment
.add(R.id.list, new ItemFragment())
- replace R.id.list
with your container id inflated in Activity
(layout passed to setContentView
)