Rafael
Rafael

Reputation: 6369

Android using onConfigurationChanged resets my listview scroll position

In my app I have chat activity with listview. I decided to use onConfigurationChanged to retain this listview with messages, while user changes screen orientation. The problem is that scroll position is resetting every time. How I can keep my scroll position for listview. In Manifest

<activity
            android:name=".ChatActivity"
            android:configChanges="keyboardHidden|orientation|screenSize"
/>

In activity

@Override
    public void onConfigurationChanged(android.content.res.Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Log.d(TAG, "orientation changed");
        chatView.setSelection(scrollPosition);
    }

Upvotes: 0

Views: 531

Answers (2)

xdamir79
xdamir79

Reputation: 49

If you write chat, you probably added for listview transcript mode = ALWAYS_SCROLL

msgListView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);

This mode scroll listview to bottom, after screen rotation. Comment it and list position will remain after rotation.

Scroll mode you can change to forced movement to end of list, like below:

chatAdapter.notifyDataSetChanged(); int pos = msgListView.getCount()-1; msgListView.setSelection(pos);

Upvotes: 0

Green goblin
Green goblin

Reputation: 9994

Remove this:

chatView.setSelection(scrollPosition);

[Edit]

//Save state
Parcelable state = listView.onSaveInstanceState();

//Restore state
listView.onRestoreInstanceState(state);

[Edit2]:

//Save
int index = mList.getFirstVisiblePosition();
View v = listView.getChildAt(0);
int top = (v == null) ? 0 : (v.getTop() - mList.getPaddingTop());

//Restore
listView.setSelectionFromTop(index, top);

Upvotes: 1

Related Questions