Get Fragment instance in Activity
Asked Answered
O

2

5

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.

Oriya answered 31/3, 2016 at 6:30 Comment(4)
you can make that method staticLilllie
Why you want to get Fragment instance? better to make one Interface and override method in Activity and called it from Fragment. This way to got all the data from Fragment A to your ActivityDampproof
use this getActivity().getSupportFragmentManager().beginTransaction() .add(R.id.container,new MyFragment).commit();Nakasuji
Use FragmentTransaction's add(int containerViewId, Fragment fragment, String tag) method and FragmentManager's findFragmentByTag(String) method.Reconcilable
C
17

Try this

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

for get the fragment

MyFragment frag = ((MyFragment) getSupportFragmentManager().findFragmentByTag("MyFragment"));
Conchoid answered 31/3, 2016 at 6:42 Comment(0)
M
0

Following this link:

All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.

Thus I would recommend:

  1. To define a interface in Fragment B.
  2. Implement the interface in activity.
  3. Then eventually, deliver the message to Fragment A.

Code example and reference.

Morrismorrison answered 31/3, 2016 at 6:39 Comment(1)
Step (3) doesn't follow from steps (1) and (2).Systematism

© 2022 - 2024 — McMap. All rights reserved.