How to call a method in a Fragment when backstack change

49 Views Asked by At

I have 2 fragments FragmentA and FragmentB

From FragmentA I open FragmentB

val transaction = fragmentManager.beginTransaction()
transaction.add(CONTAINER_VIEW_ID, FRAGMENT_B_INSTANCE, FRAGMENT_B_TAG)
transaction.addToBackStack(null)
transaction.commit()

User can back to FragmentA by both ways pressing a custom back button and pressing Phone back button. Custom button call the below method.

fragmentManager.popBackStack()

FragmentB is user adding form with API call, FragmentA onResume I call user list API and display user list. After add user in FragmentB and when back to FragmentA I need to call API again in FragmentA onResume or custom method in FragmentA to get latest users list. (FragmentA onResume won't call since not calling Activity onResume in this scenario)

How can I do this?

2

There are 2 best solutions below

1
M. AsadUllah On

if your want dont want to come back to FragmentA then you have to remove from stack when you go to FragmentB. So, in this way move from FragmentA to FragmentB and to FramentC but on coming back from FragmentC to FragmentB not to FragmentA

4
M. AsadUllah On

There are methods to call resume functions

in Activity

public class MainActivity extends AppCompatActivity {

@Override
protected void onPostResume() {
    super.onPostResume();
}

in Fragment

public class MainFragment extends Fragment {

@Override
public void onResume() {
    super.onResume();
}

Hope this works for resuming