Flo
Flo

Reputation: 1499

Android - Scroll to position in ListView in ListFragment after data of adapter has changed

I am using a ListFragment with a custom adapter, which is used to inflate the views. The data is loaded via an AsyncTaskLoader once the fragment is created.

My problem is now that I want to scroll (not smooth scroll) to a certain position to show the last selected element, i.e. The fragment gets destroyed when I select an element and I want to show the same position in the list once the fragment is displayed again.

So creating the view and everything works fine, but I do not know where to add the getListView().setSelection(x) line to scroll to a certain position. I tried to invoke it after clearing and adding the elements to the adapter in Loader<?>.onLoadFinished() function, but that does not work, I get the following exceptoins:

java.lang.IllegalStateException: Content view not yet created
  at android.support.v4.app.ListFragment.ensureList(ListFragment.java:328)
  at android.support.v4.app.ListFragment.getListView(ListFragment.java:222)
  at fs.pokemon.effect.PokemonFragment.updateData(PokemonFragment.java:239)
  at fs.pokemon.effect.PokemonFragment$2.onLoadFinished(PokemonFragment.java:129)
  ...

My question is: Is there a function/callback so I get notified, when the ListView has finished updating its content? Or how else can I scroll the View to a position after the content has loaded?

Upvotes: 1

Views: 2704

Answers (2)

Mitech
Mitech

Reputation: 410

Set the transcript mode and stackfromBottom for the listview while your listfragment activity is created. Now every time the listview is updated it will be scrolled to bottom to the latest item.

public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            getListView().setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
            getListView().setStackFromBottom(true);
}

Upvotes: 1

Flo
Flo

Reputation: 1499

Thanks to pskink comment I tried it again and noticed that the exception does not occur in setSelection() but rather in getListView() - I though my loader would reload data after the view was created, but instead it used the cached results, so onLoadFinished() was actually called, before the initialization of the fragments view was finished, thus causing an exception.

The correct way to do it is to determine the position in onLoadFinished() and then override the fragments onViewCreated() and execute getListView().setSelection(curPosition) there.

Probably also the case that the loader cleared its cache and the onLoadFinished() will be called after the onViewCreated() method has to be considered, but so far it works fine.

Upvotes: 1

Related Questions