Reputation: 1014
I added some Fragment
into a TableLayout
and I want to manage them from my container Activity
, so I used this:
Fragment fragment = (Fragment) tableLayout.getChildAt(i);
but getChildAt(int)
returns a View
and a View
could NOT cast to Fragment
Upvotes: 65
Views: 36588
Reputation: 3076
Fragments
can be very confusing at times, especially for beginners. To understand your problem, you must learn what is a Fragment
and how they are used.
To start with, a View
is something that has an existence on the screen. Examples include: TextView
, EditText
, Button
, etc. They are placed inside "layouts" written in Xml or Java/Kotlin. These layouts are shown using an Activity
.
Now, a Fragment
is not a View
. It does not have any existence on the screen at all. Instead, it's a class that simply manages a layout — kinda similar to an Activity
. If you need the View returned by your Fragment's onCreateView()
, you can directly use findViewById()
within your Activity
.
If you need a reference to your Fragment, there are two possible ways of doing this:
getFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container_viewgroup, myFragment, FRAGMENT_TAG)
.commit();
You can use:
MyFragment myFragment = (MyFragment) getFragmentManager().findFragmentByTag(FRAGMENT_TAG);
<fragment android:name="com.example.android.fragments.HeadlinesFragment"
android:id="@+id/fragmentContainer"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
You can use this:
getFragmentManager().findFragmentById(R.id.fragmentContainer);
Basically, each Activity has a FragmentManager
class that maintains all the active Fragments
, and there are two ways of finding them: Using a unique TAG that you pass while showing a fragment, or passing the container view-ID where the fragment was added.
Upvotes: 80
Reputation: 812
For people looking how to actually get a reference to the Fragment object from a View there is now a method in FragmentManager
called findFragment(View)
(reference)
//in Java
FragmentManager.findFragment(view)
//in Kotlin there is an extension function
view.findFragment()
Be careful - it will throw an IllegalStateException if the view was not added via a fragments onCreateView
.
Upvotes: 38
Reputation: 17809
You can not get a fragment like this. You will have to add fragment with a tag and retrieve it by that tag.
to add a fragment do following:
getFragmentManager().beginTransaction().add(R.id.container, fragment, "tagTofindFragment");
to get fragment:
fragment = getFragmentManager().findFragmentByTag("tagTofindFragment");
Here tagTofindFragment
is that tag that should be unique among your fragments.
Upvotes: 2