我有自定义 LinearLayout
,它是我的子视图的父视图。我正在使用 View
通过膨胀子布局将子视图添加到此父 parent.addView()
中。此 LinearLayout
包含在 ScrollView
中,因此如果有更多子视图,我可以滚动子视图。问题是,如果我在那里添加子视图,LinearLayout
高度将被忽略(由于某种原因它拉伸到全屏高度)。这种行为完全破坏了对 ScrollView
的需求。为什么会发生任何原因?我需要一些 maxHeight
参数才能工作。它应该只拉伸到最大 200dp。
布局:
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="@+id/resultList"
android:layout_width="match_parent"
android:layout_height="200dp"
android:paddingTop="@dimen/padding_medium"
android:paddingStart="@dimen/padding_medium"
android:paddingEnd="@dimen/padding_medium"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
答案 0 :(得分:0)
您可以通过使用 ConstraintLayout 的根和 ScrollView 的子级来实现此行为,该子级的高度为 wrap_content,最大高度为 200dp,使用属性 app:layout_constraintHeight_max="200dp" 和ScrollView 子元素将是具有 layout_height 到 wrap_content 的 LinearLayout。
下面是xml布局:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ScrollView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="@android:color/holo_blue_dark"
app:layout_constraintHeight_max="200dp"
app:layout_constraintVertical_bias="0"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<LinearLayout
android:id="@+id/resultList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="@dimen/padding_medium"
android:paddingStart="@dimen/padding_medium"
android:paddingEnd="@dimen/padding_medium"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
向总高度小于200dp的LinearLayout添加3个不同颜色的50dp高度的子视图后的结果如下(不需要滚动):
将 9 个不同颜色的 50dp 高度子视图添加到总高度大于 200dp 的 LinearLayout 后的结果将如下所示(需要 Scroll)(ScrollView 的最大高度为 200dp):
答案 1 :(得分:0)
从您的问题中不清楚您的布局目标是什么。在我看来,ScrollView 正在对其子项的高度进行一些假设(并且它只能有一个子项)。如果您希望 LinearLayout 有一个特定高度,在 ScrollView 本身上设置该高度。