0

I have a host acitivity with two fragments; fragment A having a recyclerview of items, and fragment B for displaying the details..

when a user click on an item, fragment A gets replaced for fragment B;

I want to save the position of the recyclerview when items are clicked..

I have trying the following..

if Fragment A..

Parcelable recyclerViewState;

in onPause I'm assigning a value for the variable as follow:

@Override
public void onPause() {
    super.onPause();

    recyclerViewState = imagesRecyclerView.getLayoutManager().onSaveInstanceState();

}

in onResume I'm retrieving the value as follows:

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

    if (recyclerViewState != null) {
        imagesRecyclerView.getLayoutManager().onRestoreInstanceState(recyclerViewState);
    }

}

however it's not working yet?

ColdFire
  • 6,764
  • 6
  • 35
  • 51
Omar Labib
  • 55
  • 9
  • Did you try with onSaveInstantState method? – Giulio Pettenuzzo Apr 10 '18 at 23:32
  • @GiulioPettenuzzo, I tried but it's not called when when the fragment is replaced! note, to check I added a log in the - if not null part - and it's running properly, i.e. the recyclerViewState is not null after replacement – Omar Labib Apr 10 '18 at 23:35
  • I am not an expert with fragment but I think you have to use somethink similar to start activity for result! Did you try to send an intent from fragment B to fragment A with the position? – Giulio Pettenuzzo Apr 10 '18 at 23:42
  • Possible duplicate of [Fragment onResume() & onPause() is not called on backstack](https://stackoverflow.com/questions/11326155/fragment-onresume-onpause-is-not-called-on-backstack) – Stanley Ko Apr 11 '18 at 01:08
  • @StanleyKou this has nothing to do with my question! – Omar Labib Apr 11 '18 at 03:25

1 Answers1

0

If you are just set fragment hidden or visible, then how about use this?

@Override
public void onHiddenChanged(boolean hidden) {
    super.onHiddenChanged(hidden);
    // Do something with boolean hidden 
}

Or, Use backstackChangedListener. https://stackoverflow.com/a/40792162/850347

getFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
    @Override
    public void onBackStackChanged() {
        if (getFragmentManager() != null) {

            Fragment topFrag = NavigationHelper.getCurrentTopFragment(getFragmentManager());

            if (topFrag != null) {
                if (topFrag instanceof YourFragment) {
                    //This fragment is being shown. 
                } else {
                    //Navigating away from this fragment. 
                }
            }
        }
    }
});
Stanley Ko
  • 3,383
  • 3
  • 34
  • 60