当我在ListView中选择一个项目时,如何保存ListView的滚动位置,并且我想在同一个ListView中返回.
假设我们有两个片段 - ListFragment和SomeOtherFragment.我们用SomeOtherFragment替换ListFragment.
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.content_frame, fragment);
transaction.addToBackStack(null);
transaction.commit();
Run Code Online (Sandbox Code Playgroud)
我知道最好的解决方案
//将ListView状态(=包括滚动位置)保存为Parcelable
Parcelable state = listView.onSaveInstanceState();
Run Code Online (Sandbox Code Playgroud)
//恢复以前的状态(包括选定的项目索引和滚动位置)
listView.onRestoreInstanceState(state);
Run Code Online (Sandbox Code Playgroud)
即使在将适配器设置为 - 后,您也可以恢复上次保存的位置 -
// 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);
Run Code Online (Sandbox Code Playgroud)
您也可以在这里参考更多细节.
当您单击 的行时ListFragment,将位置保存在 SharedPreference 中
<shared_pref_object>.putInt("scroll_position",position);
Run Code Online (Sandbox Code Playgroud)
OtherFragment当你从->回来时使用这个ListFragment
<editor_obj>.getInt("scroll_position",0);
Run Code Online (Sandbox Code Playgroud)
将其设置为滚动位置:
listview.setSelection(<editor_obj>.getInt("scroll_position",0));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2883 次 |
| 最近记录: |