首页 > 解决方案 > Android UI - 动态按钮对齐更改

问题描述

我有以下 xml

<ConstraintLayout>
    <NestedScrollView>
        <ConstraintLayout>
            <RecycleView/>
        </ConstraintLayout>
    </NestedScrollView>
    <Button BottomTo_BottomOf = parent/>
</ConstraintLayout>

当我加载屏幕时,我希望按钮粘在屏幕底部。我在recycleview中动态加载一些元素(基于用户操作),一旦recycleview的元素超过屏幕大小,那么我希望按钮对齐方式从屏幕底部更改到内容的末尾,并且一旦用户滚动就可见所有内容

标签: androidandroid-layoutuser-interfaceandroid-fragmentsandroid-constraintlayout

解决方案


将这些属性添加到Button

    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"

将这些属性添加到NestedScrollView

    android:layout_width="match_parent"
    android:layout_height="0dp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toTopOf="@+id/bottomButtonId" <--Id of bottom button-->

作为参考,请尝试以下代码:

<?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:layout_width="match_parent"
    android:layout_height="match_parent">
    <androidx.core.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toTopOf="@+id/button6">
        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/rvMain"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:overScrollMode="never"
                tools:listitem="@layout/imagepost_buttons"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"/>
        </androidx.constraintlayout.widget.ConstraintLayout>
    </androidx.core.widget.NestedScrollView>

    <Button
        android:id="@+id/button6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Bottom Button"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

推荐阅读