代码之家  ›  专栏  ›  技术社区  ›  jakub

ConstraintLayout-水平打包项目,但不设置宽度以匹配父项

  •  -1
  • jakub  · 技术社区  · 5 年前

    我想实现这个简单的观点 enter image description here

    但是,当设置约束时

    <?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">
    
        <TextView
            android:id="@+id/upgradeTo"
            style="@style/NewText.H2.Primary"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="right"
            android:text="UPGRADE TO"
            app:layout_constraintBaseline_toBaselineOf="@id/premium"
            app:layout_constraintEnd_toStartOf="@+id/premium"
            app:layout_constraintStart_toStartOf="parent" />
    
        <TextView
            android:id="@+id/premium"
            style="@style/NewText.H2.Accent"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:background="@drawable/round_rect_separator"
            android:backgroundTint="#fff3f8"
            android:paddingLeft="12dp"
            android:paddingTop="4dp"
            android:paddingRight="12dp"
            android:paddingBottom="4dp"
            android:text="PREMIUM"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@+id/upgradeTo"
            app:layout_constraintTop_toTopOf="parent" />
        
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    我的观点没有被压缩,而是被扩展了 enter image description here

    通常,我在这种情况下使用 android:layout_width=match_parent 然而,在这种情况下,我不能,因为我在PREMIUM上的彩色背景也会延伸。

    有没有其他方法可以不使用 match_parent ? 或者,唯一的方法是将我的视图(PREMIUM)的背景重构为单独的 ImageView ).

    1 回复  |  直到 5 年前
        1
  •  1
  •   Muhammad Saad Rafique    5 年前

    您只需在文本视图中添加以下行:

    app:layout_constraintHorizontal_chainStyle=”packed”
    

    有关详细信息,请访问此链接: https://medium.com/@nomanr/constraintlayout-chains-4f3b58ea15bb