ScrollView 内的Android约束布局高度无效

标签 android xml scrollview android-constraintlayout android-relativelayout

在Android中,我想实现屏幕上固定高度的 ScrollView ,里面的内容也有固定高度。

ScrollView 高度为 300dp,直接子级(相对布局)为 500dp,与顶部的 TextView 距离为 301dp。这意味着在我到达 TextView 之后,还有 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 的 TextView ,而不是在底部显示 200dp 的空白空间。

ConstraintLayout Scroll

有人可以解释为什么约束布局给了我这种奇怪的行为吗?
根据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/

相关文章:

xml - VB.NET XPathDocument.CreateNavigator 抛出 "debuggerDisplayProxy"错误

ios - 如何为不占用整个父 View 的 ScrollView 设置约束

java - 无法让编辑文本在 ScrollView 中工作

android - 如何使用android-simple-facebook登录?

android - 将 Lottie Android 与矢量图像 (xml) 或 svg 图像一起使用?

php - 解析 WordPress XML,斜杠 :comments syntax?

android - Android 中 ScrollView 中的广告对齐方式

javascript - 如果应用程序存在,链接到打开的 facebook 应用程序,否则网页

Android 支持设计库 CoordinatorLayout 与 webview 问题

xml - 无法从 GO 中的 XML 中提取正确的数据