0

I have a list fragment.

When the user click on a list item, i replace the list fragment with a news fragment. When the user come back (using addToBackStack), the list scrolls to the top.

I would like my list to remain to the same scroll level when the user pressed the list item..is that possible?how can i get this result?

this is my code where i replace the list fragment:

myFragment myFragment = new myFragment();

    myFragment.setArguments(bundle);
                FragmentTransaction ft = getActivity().getSupportFragmentManager()
                        .beginTransaction();
                ft.replace(R.id.phone_container, myFragment);
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft.addToBackStack(null);
                ft.commit();

I have tried something like this but i get no result:

public void onResume() {
    super.onResume();
    Log.i("log", "onResume()");

      setListAdapter(adapter);
      if(index!=-1){
         this.getListView().setSelectionFromTop(index, top);
      }
}

public void onPause() {
    super.onPause();
    Log.i("log", "onPause()");
    try {
        index = this.getListView().getFirstVisiblePosition();
        View v = this.getListView().getChildAt(0);
        top = (v == null) ? 0 : v.getTop();
    } catch (Throwable t) {
        t.printStackTrace();
    }
}
menu_on_top
  • 2,555
  • 14
  • 42
  • 70

1 Answers1

0

When you remove the fragment from the view hierarchy you actually destroy the view but not the fragment. so when it re-attaches it calls onCreateView again. This is why your list is scrolled at the top again.

the way to save the state is store it in instance variables and then use onCreateView again to scroll to the last position as your code does (after the adapter is filled of-course).

This might be helpful for more details. How can I maintain fragment state when added to the back stack?

Community
  • 1
  • 1
DArkO
  • 14,990
  • 10
  • 56
  • 82
  • may i have some code for this please? :) – menu_on_top Oct 13 '13 at 17:28
  • I cannot write the specific code you need. but its simple, you already save the index in your onResume method. just wait until the data is loaded in the list with the adapter to restore it as opposed to onResume(). initially you will have index with the value 0. just write it as you would expect to load to a specific index as the screen shows up the first time. – DArkO Oct 13 '13 at 18:03
  • Actually, when i return to my listView, i can see the small images in the list items to flash for a second.Does this means something? – menu_on_top Oct 13 '13 at 19:34
  • What are you using to load the images. that means they are being redrawn, but since you have them in memory they are drawn immediately. Just try to do what i told you. save the index on onPause and use it after filling the listView with items to scroll to that index.(the first launch will be 0 so you are good to go regardless) – DArkO Oct 13 '13 at 21:32