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.

Community
  • 1
  • 1
Zar E Ahmer
  • 33,936
  • 20
  • 234
  • 300
  • you can make that method static – Vivek Mishra Mar 31 '16 at 06:35
  • 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 Activity – M D Mar 31 '16 at 06:38
  • use this getActivity().getSupportFragmentManager().beginTransaction() .add(R.id.container,new MyFragment).commit(); – Jigar Mar 31 '16 at 06:38
  • Use FragmentTransaction's add(int containerViewId, Fragment fragment, String tag) method and FragmentManager's findFragmentByTag(String) method. – random Mar 31 '16 at 06:42

2 Answers2

17

Try this

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

for get the fragment

MyFragment frag = ((MyFragment) getSupportFragmentManager().findFragmentByTag("MyFragment"));
arun
  • 1,728
  • 15
  • 15
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.

Rohit Arya
  • 6,751
  • 1
  • 26
  • 40