簡體   English   中英

Android 2視圖的簡單布局

[英]Android simple layout of 2 views

無法理解如何實現簡單的事情。 我需要具有以下行為的2個視圖的布局:

文字短時,按鈕應位於文字右側

當文本較長時,它將變為橢圓形,並且按鈕始終可見且為全角

現在我知道該按鈕不在屏幕上

您可以使用ConstraintLayout實現此目的。 這是一個模板:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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">

    <TextView
        android:id="@+id/text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Hello world"
        android:maxLines="1"
        android:ellipsize="end"
        app:layout_constraintHorizontal_chainStyle="packed"
        app:layout_constraintHorizontal_bias="0"
        app:layout_constraintWidth_default="wrap"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@+id/button"
        app:layout_constraintBottom_toBottomOf="parent"/>

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="HELLO WORLD"
        app:layout_constraintLeft_toRightOf="@+id/text"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBaseline_toBaselineOf="@+id/text"/>

</android.support.constraint.ConstraintLayout>

初始設置為:

  • 創建一個包含文本和按鈕的水平鏈
  • 將鏈樣式設置為“壓縮”,以便視圖之間沒有空間
  • 將水平偏差設置為0,以使打包視圖向左擁抱

神奇之處在於TextView的寬度和app:layout_constraintWidth_default屬性。 通過將寬度設置為0dp並包裝“默認寬度”,我們告訴Android為視圖提供盡可能多的空間來容納其內容,只要它適合約束即可 當文本確實很長時,約束將阻止其將按鈕從屏幕右側推下。

在此處輸入圖片說明

在此處輸入圖片說明

暫無
暫無

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

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