Android中,ScrollView内的ConstraintLayout高度不起作用。

5

在Android中,我想要实现一个固定高度的滚动视图,并且里面的内容也有固定的高度。

滚动视图的高度是300dp,直接子元素(相对布局)为500dp,文本视图从顶部距离为301dp。这意味着在到达文本视图后,我仍然可以从相对布局的底部拖动200dp的空间。

enter image description here

我使用下面的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的文本视图,而不会显示底部200dp的空白。

ConstraintLayout Scroll

有人能解释一下为什么约束布局会给我带来这种奇怪的行为吗? 根据Differences between ConstraintLayout and RelativeLayout,约束布局“具有相对布局和线性布局的双重功能”,它应该能够实现相对布局所能实现的功能。


你想要实现什么目标? - Ibrar Khan
我想请人帮忙让约束布局的高度生效,并解释为什么约束布局会出现这种奇怪的行为。我展示的例子只是为了让你有一个视觉上的理解。 - BabyishTank
2个回答

6

试试这个:

<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>

似乎约束布局中存在一个 bug 或者布局高度不能在滚动视图中应用到约束布局,但可以使用约束布局的最小高度属性。

问题已解决,应用最小高度会使约束布局的高度生效。谢谢。 - BabyishTank
@BabyishTank 我很乐意帮助你。 - Ibrar Khan
谢谢!你在数小时后救了我... - Avital

1

ScrollView 中添加 android:fillViewport="true"


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接