How can I get Fragment from View?
Solution 1:
I don't understand why people are down-voting your question. 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:
1) If you added the Fragment programmatically like this
getFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container_viewgroup, myFragment, FRAGMENT_TAG)
.commit();
You can use:
MyFragment myFragment = (MyFragment) getFragmentManager().findFragmentByTag(FRAGMENT_TAG);
2) If you added the Fragment inside an XML layout like this:
<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.
Solution 2:
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
.
Solution 3:
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.