如何在不使用 NestedScrollView 的情况下滚动 ListView?

Posted

技术标签:

【中文标题】如何在不使用 NestedScrollView 的情况下滚动 ListView?【英文标题】:How to scroll a ListView without using NestedScrollView? 【发布时间】:2020-04-09 13:01:00 【问题描述】:

这个问题在过去可能至少被问过十几次。看过以前的回复,但似乎仍然无法正常工作

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/colors_list"
    android:layout_
    android:layout_ />

我确实有一个我不想使用的可行解决方案,因为我被告知不需要使用NestedScrollView,因为ListView 本身是可滚动的。然而,如果我自己使用它,我似乎无法滚动我的ListView。为什么?

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_
android:layout_
android:background="?attr/layout_background_color">

<LinearLayout
    android:layout_
    android:layout_
    android:layout_marginTop="?attr/actionBarSize"
    android:orientation="vertical">

    <ListView
        android:id="@+id/colors_list"
        android:layout_
        android:layout_ />

</LinearLayout>

</android.support.v4.widget.NestedScrollView>

【问题讨论】:

【参考方案1】:

我猜这里最大的问题是你将ListView 设置为android:layout_height="wrap_content",它不能滚动,因为它的高度总是由它的孩子增加。

试试android:layout_height="match_parent"。 (魔术发生了!)

<LinearLayout
    android:layout_
    android:layout_
    android:layout_marginTop="?attr/actionBarSize"
    android:orientation="vertical">

    <ListView
        android:id="@+id/colors_list"
        android:layout_
        android:layout_ />

</LinearLayout>

【讨论】:

感谢萨比尔!不幸的是,这不起作用。当我使用您建议的代码时,填充的 ListView 不会滚动。 schemas.android.com/apk/res/android" android:layout_ android:layout_ android:layout_marginTop="?attr/actionBarSize" android:orientation="vertical"> 【参考方案2】:

您的嵌套滚动视图总是推动列表视图向下滚动。用滚动视图包装 listview 或 recyclerview 是不好的方法,你的 ui 可能很重。尝试另一种方法,例如 recyclerview 多视图持有者,以更好地使用列表构建滚动 ui

【讨论】:

请通过示例、代码 sn-p 或任何文档文章来支持您的回答

以上是关于如何在不使用 NestedScrollView 的情况下滚动 ListView?的主要内容,如果未能解决你的问题,请参考以下文章

如何在viewPager的视图顶部使用nestedScrollView中的viewpager

如何使用 NestedScrollView 滚动以在 SliverAppBar 上使用堆栈圆形头像?

如何在android中使用SwipeRefreshLayout和imageView进入NestedScrollView

NestedScrollView的使用

如何以编程方式在 NestedScrollView 中显示滚动条。

如何在Android中设置NestedScrollView的最大高度?