Android:滚动整个片段,里面有ListView



我的片段布局文件中有以下结构:

- ScrollView
- ConstraintLayout
- CardView
- *some stuff here*
- CardView
- ListView
- *list header*
- *list items generated with a custom adapter*

如果我去掉外部的ScrollView,我可以看到ListView的全部内容,如果它大于第二个CardView的剩余空间,我可以滚动它。第一个CardView保持不变,但第二个的内容是可滚动的。

然而,我想滚动整个片段。我希望第二个CardView展开并包含整个ListView,如果我向上或向下滚动,第一个也会移动。

我尝试了几种高度设置的组合。向您展示我的实际布局XML毫无意义,因为它一团糟。我想重新开始。有可能实现吗?

编辑:

我知道ListView本身就是一个滚动容器,但我认为滚动整个内容是一种非常常见的需求,所以我不明白为什么它很难工作。

好吧,在组合多个答案之后,我就有了我需要的解决方案。

第一

我需要使用NestedScrollView而不是常规的ScrollView

它解决了两个滚动容器(ScrollViewListView(之间的冲突。

参考:Android:滚动视图与嵌套滚动视图

注意:我的列表内容是动态的,所以它可能太短,无法填满剩余的空间。我不得不在NestedScrollView上设置android:fillViewport="true"。如果列表比剩余空间长,则不会造成任何问题。

layout.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.cardview.widget.CardView
android:id="@+id/card1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!-- NOTE: constraints properties are missing from here for easier reading -->
<!-- card content here -->
</androidx.cardview.widget.CardView>
<androidx.cardview.widget.CardView
android:id="@+id/card2"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!-- NOTE: constraints properties are missing from here for easier reading -->
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<!-- NOTE: this will change in step 3 -->
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.core.widget.NestedScrollView>

第二

按照上面的步骤将使ListView折叠到其第一个项目的高度。为了解决这个问题,我需要从ListView创建一个子类,并覆盖它的onMeasure()方法,这样它就可以在运行时计算出合适的高度。

参考:Android-包含ExpandableListView的NestedScrollView没有';t展开时滚动

NonScrollListView.java

package my.package.name
import ...
public class NonScrollListView extends ListView {

// NOTE: right click -> create constructors matching super
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int heightMeasureSpec_custom = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec_custom);
ViewGroup.LayoutParams params = getLayoutParams();
params.height = getMeasuredHeight();
}
}

第三

我需要在布局XML中使用自定义视图,而不是常规的ListView

layout.xml摘录

<my.package.name.NonScrollListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

通过这种方式,我设法使它发挥作用。即使我点击ListView区域,两张牌也会一起滚动。

我不知道它是否会导致列表太长的性能问题,因为我的列表最多包含几十个项目,但我对低端Galaxy A20e没有问题。

最新更新