簡體   English   中英

如何將按鈕同時限制在屏幕底部和文本視圖

[英]How can I constrain a button to the bottom of the screen and a text view at the same time

我有以下簡單的應用程序設計。 工具欄、textview 和按鈕。

安卓應用布局

如何構建此布局設計,以便:

  1. 當文本很小時,按鈕被限制在屏幕底部
  2. 當文本較長時,它不會在按鈕下方延伸,而是拉伸滾動視圖的高度

編輯:這是下面描述的@MariosP 的解決方案。 將按鈕約束到 textview 和屏幕底部。 但是,如果您這樣做,您會看到按鈕默認為平均兩個約束,因此它在兩個約束之間垂直浮動,這不是我想要的。 訣竅是在按鈕上使用app:layout_constraintVertical_bias="1" 這告訴布局您不希望按鈕位於其垂直約束的中間,而是希望位於兩個約束的最底部(底部邊緣)。 在 0 和 1 之間更改偏置數將使按鈕沿着這些垂直約束滑動。 如果您正在獲得按鈕懸停在其他文本視圖上的布局,則此信息將為您提供幫助。

您可以使用帶有 ConstraintLayout 子級的 ScrollView 來實現此行為。 下面是 xml 布局:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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"
    android:background="@android:color/holo_blue_dark"
    android:fillViewport="true">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/constraintLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/button"
            android:layout_width="200dp"
            android:layout_height="80dp"
            android:text="Button"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintStart_toStartOf="parent"
            app:backgroundTint="@android:color/holo_red_light" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua"
            android:textColor="@android:color/white"
            android:textSize="16sp"
            android:layout_margin="40dp"
            app:layout_constraintVertical_bias="0"
            app:layout_constraintBottom_toTopOf="@+id/button"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/toolbar" />

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="0dp"
            android:layout_height="60dp"
            android:background="@android:color/holo_green_light"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</ScrollView>

帶有小文本的結果:

在此處輸入圖像描述

長文本的結果(滾動到底部后):

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM