我有一个很长的ListView,用户可以在返回到前一个屏幕之前滚动.当用户再次打开此ListView时,我希望列表滚动到与以前相同的位置.对如何实现这一点有什么 idea 吗?

推荐答案

试试这个:

// 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);

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.

Android相关问答推荐

Android Jetpack编写如何在简单单击后显示工具提示

致命信号6(SIGABRT)MAUI应用程序在android net发布时崩溃.8、使用强制屏幕方向和并发GC

在Android Studio中陷入了不兼容的Gradle版本的循环

如何在Jetpack Compose中使用Box Composable来实现这种布局?

登录方法显示为空列表,即使它显示的是Firebase身份验证控制台

Kotlin Android VS Kotlin多平台

触发PurchasesUpdatedListener回调时,billingClient.launchBillingFlow之前设置的成员变量丢失

我们可以使用KSP读取类中变量的值吗?

如何检测低性能 Android 设备进行条件动画渲染?

如何在 compose 中使用可变对象?

如何禁用自动登录 google play games services android unity?

在 Material 3 TopAppBar 代码的哪个位置定义了填充?

如何在一个活动中预加载图像然后在另一个活动中加载它们?

如何用jetpack compose实现垂直李克特量表

Jetpack Compose 动画性能问题

在 Jetpack Compose 中更改列中子项的对齐方式

喷气背包组成影子奇怪的行为

JetPack Compose - 卡片行中的权重()不起作用

从expose 的 dropdownMenu 可组合、jetpack 组合中 Select 选项时,不会触发文本字段的 onValueChange

在 Jetpack Compose 中找不到 Path 的减号()