MickeyR
MickeyR

Reputation: 1887

What is causing ListView to maintain its scroll-position after orientation change?

I have an Activity containing a ListView. I populate the list view using a SimpleCursorAdapter. When I run the app, I can manually scroll down in the ListView (e.g. to the 10th item). Then when I rotate my phone - this destroys and re-creates my Activity and the ListView is made afresh as expected.

But, on my phone after rotating, the re-created Activity shows my ListView still at my manual scroll position (in this example, the 10th row). I'm pretty sure my code is not calling ListView.setSelection(int) so what is causing this re-positioning of the ListView ?

This might seem pretty handy, but its not what I want. Is it part of ListViews behaviour ? If so, how can stop/override this re-positioning ?

Upvotes: 4

Views: 2382

Answers (3)

Sergey
Sergey

Reputation: 1050

ListView restores its state (including scroll position) after screen rotation the same way and for the same reason as for example EditText preserves the text you typed in it. It is how the Android framework is designed. You can stop this save/restore behavior by setting android:saveEnabled="false" attribute for the ListView in the xml layout file. Or you can call setSaveEnabled(false) method on the ListView for the same purpose.

Upvotes: 0

MickeyR
MickeyR

Reputation: 1887

Reading around the topic some more....

View states are stored automatically (including my ListView). This is handled by the default implementation of onSaveInstanceState() / onRestoreInstanceState(). Using the debugger I can see that savedInstanceState includes an entry from my ListView - so that is what is automatically repositioning it. To stop that in my Activity I can just override onSaveInstanceState().

Upvotes: 4

slkorolev
slkorolev

Reputation: 6001

Did you use ListActivity as a base class for your activity? If yes then it's likely the feature as it overrides onRestoreInstanceState. I would try to inherit from simple Activity.

Upvotes: 0

Related Questions