如何将两个视图对齐并分别位于上下两侧,并在顶部视图增大时推动底部视图?

3
我基本上在视图顶部对齐了一个EditText,视图底部有一个RecyclerView,也可以增长(最新项目位于底部)。使用约束布局可以轻松实现,但我的问题是当EditText增长时,它应该开始向下推列表。但列表最初是与父级底部对齐的。(而且一切都应该可滚动)我希望这张图片能让事情更清楚。

enter image description here

2个回答

2
这里的诀窍是避免形成垂直链(使顶部的EditText始终保持在原位),并利用RecyclerView上的app:layout_constrainedHeight属性,使其在EditText增长时收缩。
<?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/list"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constrainedHeight="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/text"
        app:layout_constraintVertical_bias="1"/>

</androidx.constraintlayout.widget.ConstraintLayout>

使用android:layout_height="wrap_content"app:layout_constrainedHeight="true"属性,再加上顶部和底部约束,意味着RecyclerView的高度始终只有其项或EditText下方可用空间中较小的那个。 app:layout_constraintVertical_bias="1"属性确保当列表不填满屏幕时,它位于底部。

2

我想补充一下之前的回答,如果您想要能够滚动布局,您可以使用类似于以下内容的东西:

<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="wrap_content">

    <EditText
        android:id="@+id/edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@id/edit_text"
        app:layout_constraintVertical_bias="1.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.core.widget.NestedScrollView>

这将使所有内容按照您想要的方式对齐,并且您可以向下滚动以查看完整的recyclerViewNestedScrollView 将确保一切运行顺畅。


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