Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I save the ListView's scroll position

Tags:

android

How can I save the ListView's scroll position when I choose one item in ListView, and I want to return back in same ListView .

Suppose we have two fragments – ListFragment and SomeOtherFragment. We replace ListFragment with SomeOtherFragment.

    FragmentManager manager = getFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();

    transaction.replace(R.id.content_frame, fragment);
    transaction.addToBackStack(null);
    transaction.commit();
like image 896
android java Avatar asked May 14 '15 09:05

android java


2 Answers

The best solution I know

// Save the ListView state (= includes scroll position) as a Parcelable

Parcelable state = listView.onSaveInstanceState();

// Restore previous state (including selected item index and scroll position)

listView.onRestoreInstanceState(state);

You can also restore the last saved position even after setting adapter as -

// Save the ListView state (= includes scroll position) as a Parceble
Parcelable state = listView.onSaveInstanceState();

// e.g. set new items
listView.setAdapter(adapter);

// Restore previous state (including selected item index and scroll position)
listView.onRestoreInstanceState(state);

You can also refer here for more details.

like image 140
Narendra Singh Avatar answered Nov 16 '22 03:11

Narendra Singh


When you click on row of ListFragment, save the position in SharedPreference

<shared_pref_object>.putInt("scroll_position",position);

Use this when you come back from OtherFragment -> ListFragment

<editor_obj>.getInt("scroll_position",0);

set this as scroll position :

listview.setSelection(<editor_obj>.getInt("scroll_position",0));
like image 28
Kushal Avatar answered Nov 16 '22 03:11

Kushal