How to scroll to the top of ListFragment

My position: I have two ListFragments (call them A and B), which are controlled by one activity that stores permalinks to both of these fragments. When I click the button in Fragment A, I replace that with Fragment B. The problem starts when I do the next thread.

A → B → (scroll) → (back button) → B

In this case, when I go back to fragment B again, the previous scroll position is preserved, which I don't want. Instead, I would like Fragment B to start with a ListView at the top of its content.

Things I've tried that don't do anything:

  • Call setSelection(0)

    inonActivityCreated

  • Call setSelectionAfterHeaderViews()

    inonActivityCreated

  • Call smoothScrollToPosition(0)

    inonActivityCreated

Interestingly, they all work if I run post

them on Runnable. However, when I do this, a strange flickering appears the second time when I open fragment B.

So how do I get Fragment B to automatically scroll to the top every time it is anchored to its parent Activity

? I feel like there must be something blindingly obvious that I am missing, but right now I am really stumped.

+3


source to share


1 answer


You are calling the correct methods, but you are calling them in the wrong place.

I assume you have code that switches between fragments and you call it when an element is clicked in A. So whenever you make a switch, set scroll up, something along these lines:



protected void switchList() {
    ListFragment a = (ListFragment) getFragmentManager().findFragmentByTag("a");
    ListFragment b = (ListFragment) getFragmentManager().findFragmentByTag("b");
    b.getListView().setSelectionAfterHeaderView();
    getFragmentManager().beginTransaction().hide(a).show(b).addToBackStack(null).commit();
}

      

And one important note: never keep permalinks to fragments in your actions. Whenever you need a Fragment, get it from the FragmentManager. This is critical because when the configuration changes (for example, when the device is rotated or when the application is paused and resumed), the fragments are recreated and the contained link leads to a dead fragment. This is not only a serious leak, but it will prevent your code from working. any change you make to the saved snippet is not visible on the screen because the screen contains the newly created snippet.

+1


source







All Articles