问题描述
我的片段布局文件具有以下结构:
- 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
。
它解决了两个滚动容器(ScrollView
和ListView
)之间的冲突。
参考:Android: ScrollView vs NestedScrollView
注意:我的列表内容是动态的,因此可能太短而无法填充剩余空间。我必须在android:fillViewport="true"
上设置NestedScrollView
。如果列表的长度大于剩余空间,则不会造成任何麻烦。
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 - NestedScrollView which contains ExpandableListView doesn't scroll when expanded
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上我没有问题。