0

I have two fragments, Fragment A and Fragment B. Fragment A contains 4 tabs as shown below:

enter image description here

Tab 3 has recycler view, from which user will select an option. Now user will go to Fragment B, and does something. When he is done, the call will again be back to fragment A and now Tab 4 will be highlighted and data in 4th tab will be loaded.

So far, I am able to go back to fragment A. But from there, I am not able switch to tab 4 and load data. Upon checking I found that, when callback returned to fragment A, that was still not visible. Hence tab was not switched. How can I accomplish this?

Nick Cardoso
  • 20,807
  • 14
  • 73
  • 124
Nitish
  • 3,097
  • 13
  • 45
  • 80

1 Answers1

0

You can't update FragmentA directly because it is paused. What you can do is make FragmentB a DialogFragment and use targetFragment to get a result (a lot like startActivityForResult)

In FragmentA, at the place you launch FragmentB add:

//RC_FRAGMENT_B is just an int constant to identify the result later
fragmentB.setTargetFragment(FragmentA.this, RC_FRAGMENT_B); 

And Implement:

public static final int RC_FRAGMENT_B = 1666;
public static final int RC_SUCCESS = 1888;

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if ( requestCode == RC_FRAGMENT_B && resultCode == RC_SUCCESS ) {
         //change tab, etc.
    }
}

Then in FragmentB, when you are finished, use:

Fragment target = getTargetFragment();
if (target != null) {
    //FragmentA.RC_SUCCESS result code needs to be a constant indicate to FragmentA what to do
    target.onActivityResult(getTargetRequestCode(), FragmentA.RC_SUCCESS, getActivity().getIntent());
}
Nick Cardoso
  • 20,807
  • 14
  • 73
  • 124
  • I can't convert fragment B to dialog. In fragment B, That is a web view, where I am charging money from users. Is there any way to know when fragment becomes visible? – Nitish Feb 24 '17 at 11:22
  • Yes, the onResume method, but FragmentA.onResume wont happen until after FragmentB.onPause (too late). You can put whatever you want inside a fragment dialog though. It's not the same as an AlertDialog – Nick Cardoso Feb 24 '17 at 11:26