Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Fragment instance in Activity

I have added Fragment to Activity like

getSupportFragmentManager().beginTransaction()
                    .add(R.id.container,new MyFragment).commit();

where container is the id of FrameLayout

 <FrameLayout
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

Now how could i get the instance of Fragment in Activity like this

I have to call a method of Fragment A after getting result from Fragment B.

I have created an interface in Fragment B and implemented it in Activity.Now i have to pass the result to Fragment A. I am unable to get the instance of Fragment A.

One thing i don't wanna do is to create a private instance of Fragment A in Activity and call it's method.

like image 855
Zar E Ahmer Avatar asked Mar 31 '16 06:03

Zar E Ahmer


People also ask

How do I find a fragment in an activity?

Often we need to lookup or find a fragment instance within an activity layout file. There are a few methods for looking up an existing fragment instance: ID - Lookup a fragment by calling findFragmentById on the FragmentManager. Tag - Lookup a fragment by calling findFragmentByTag on the FragmentManager.

How do you find a fragment instance?

To get the current fragment that's active in your Android Activity class, you need to use the supportFragmentManager object. The supportFragmentManager has findFragmentById() and findFragmentByTag() methods that you can use to get a fragment instance.

How do I get NavController in fragment?

To retrieve the NavController for a fragment, activity, or view, use one of the following methods: Kotlin: Fragment. findNavController()

Can a fragment contain an activity?

A fragment represents a modular portion of the user interface within an activity. A fragment has its own lifecycle, receives its own input events, and you can add or remove fragments while the containing activity is running.


1 Answers

Try this

getSupportFragmentManager().beginTransaction()
                .add(R.id.container,new MyFragment(),"MyFragment").commit();

for get the fragment

MyFragment frag = ((MyFragment) getSupportFragmentManager().findFragmentByTag("MyFragment"));
like image 193
arun Avatar answered Sep 19 '22 18:09

arun