You can see everywhere written that an activity can be converted into fragment very easily but what to do when you have to call a fragment for result from another fragment it is kind of look weird but it is a scenario you can face when you have a fragment and then have to call different fragments from it to get result and show that result in your fragment (earlier one).
But there is a solution for this problem as well. All you have to do is implement your activity (calling all those fragments) with FragmentManager.OnBackStackChangeListener and then bind this listener to your FragmentManager object. Now in the implementation of this listener call a method of your fragment you want to call when that fragment is popout of the BackStack like
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public class MainActivity extends AppCompatActivity implements FragmentManager.OnBackStackChangedListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); frame = (FrameLayout) findViewById(R.id.content_frame); TaskListFragment fr= new TaskListFragment(); fm.beginTransaction().add(R.id.content_frame,fr,"tasklist").commit(); fm.addOnBackStackChangedListener(this); } @Override public void onBackStackChanged() { int backStackEntryCount = getFragmentManager().getBackStackEntryCount(); if(backStackEntryCount > 0){ TaskListFragment currFrag = (TaskListFragment)fm.findFragmentByTag("add_task"); currFrag.onReturnFromBackStack(); //implement this method in your fragment class } } } |
and you can do anything inside this method of your fragment. But remember to add each of your fragment to backstack as this listener is called only when you pop out a earlier fragment from back stack.