在Android中,我想实现屏幕上固定高度的 ScrollView ,里面的内容也有固定高度。
ScrollView 高度为 300dp,直接子级(相对布局)为 500dp,与顶部的 TextView 距离为 301dp。这意味着在我到达 TextView 之后,还有 200dp 的底部空间供我从相对布局高度滚动。
我设法使用下面的 XML 创建所需的效果。
<ScrollView
android:layout_width="match_parent"
android:layout_height="300dp" >
<RelativeLayout
android:layout_width="match_parent"
android:background="#FFC0CB"
android:layout_height="500dp" >
<TextView
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:id="@+id/new_realm_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="301dp"
android:text="long text" />
</RelativeLayout>
</ScrollView>
但是问题来了,如果我将相对布局更改为约束布局,现在滚动只会向上滚动到高度 310dp 的 TextView ,而不是在底部显示 200dp 的空白空间。
有人可以解释为什么约束布局给了我这种奇怪的行为吗?
根据Differences between ConstraintLayout and RelativeLayout ,约束布局“兼具Relative Layout和Linear layout的双重威力”,应该能做到relative layout所能做到的。
最佳答案
尝试这个:
<ScrollView android:layout_width="match_parent"
android:layout_height="300dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:background="#FFC0CB"
android:minHeight="500dp"
android:layout_height="500dp" >
<TextView
android:id="@+id/new_realm_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="301dp"
android:text="long text"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
似乎约束布局中存在错误或布局高度无法应用于 ScrollView 中的约束布局,但您可以在约束布局中使用最小高度属性。
关于 ScrollView 内的Android约束布局高度无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61176704/