返回 ListView 时保持/保存/恢复滚动位置

Maintain/Save/Restore scroll position when returning to a ListView(返回 ListView 时保持/保存/恢复滚动位置)
本文介绍了返回 ListView 时保持/保存/恢复滚动位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很长的 ListView,用户可以在返回前一个屏幕之前滚动它.当用户再次打开此 ListView 时,我希望将列表滚动到与之前相同的位置.关于如何实现这一点的任何想法?

I have a long ListView that the user can scroll around before returning to the previous screen. When the user opens this ListView again, I want the list to be scrolled to the same point that it was previously. Any ideas on how to achieve this?

推荐答案

试试这个:

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

// ...

// restore index and position
mList.setSelectionFromTop(index, top);

说明:

ListView.getFirstVisiblePosition() 返回顶部可见列表项.但是这个item可能会被部分滚动出视图,如果你想恢复列表的确切滚动位置你需要得到这个偏移量.所以 ListView.getChildAt(0) 返回顶部列表项的 View,然后 View.getTop() - mList.getPaddingTop()返回它与 ListView 顶部的相对偏移量.然后,为了恢复 ListView 的滚动位置,我们调用 ListView.setSelectionFromTop() 并使用我们想要的项目的索引和一个偏移量来定位它的顶部边缘.ListView 的顶部.

Explanation:

ListView.getFirstVisiblePosition() returns the top visible list item. But this item may be partially scrolled out of view, and if you want to restore the exact scroll position of the list you need to get this offset. So ListView.getChildAt(0) returns the View for the top list item, and then View.getTop() - mList.getPaddingTop() returns its relative offset from the top of the ListView. Then, to restore the ListView's scroll position, we call ListView.setSelectionFromTop() with the index of the item we want and an offset to position its top edge from the top of the ListView.

这篇关于返回 ListView 时保持/保存/恢复滚动位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to target newer versions in .gitlab-ci.yml using auto devops (java 11 instead of 8 and Android 31 instead of 29)(如何在.gitlab-ci.yml中使用自动开发工具(Java 11而不是8,Android 31而不是29)瞄准较新的版本)
Android + coreLibraryDesugaring: which Java 11 APIs can I expect to work?(Android+core LibraryDesugering:我可以期待哪些Java 11API能够工作?)
How to render something in an if statement React Native(如何在If语句中呈现某些内容Reaction Native)
How can I sync two flatList scroll position in react native(如何在本机Reaction中同步两个平面列表滚动位置)
Using Firebase Firestore in offline only mode(在仅脱机模式下使用Firebase FiRestore)
Crash on Google Play Pre-Launch Report: java.lang.NoSuchMethodError(Google Play发布前崩溃报告:java.lang.NoSuchMethodError)