ConstraintLayout-wrap_content + toRightOf布局问题

时间:2019-11-01 12:27:31

标签: android android-constraintlayout

我正在使用约束布局,并且试图使textview在准则的右侧,并且还包装其宽度。但是textview没有使用约束 "app:layout_constraintLeft_toRightOf="@id/guideline1"由于某种原因

enter image description here

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout android:id="@+id/chat_model"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginRight="15dp"
    android:layout_marginTop="15dp"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <android.support.constraint.Guideline
        android:id="@+id/guideline1"
        android:layout_width="1dp"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent=".25" />

    <TextView
        android:id="@+id/texview_chatmodel_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/bubble_user"
        android:padding="8dp"
        android:text="Username: aaaaaaaa aaaaa aaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
        android:textColor="@color/colorBlack"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toRightOf="@id/guideline1"
        android:gravity="right"/>

</android.support.constraint.ConstraintLayout>

当我将textview的宽度设置为0时可以使用

android:layout_width="0dp"

但是,这会导致短消息一直延伸到指南的所有地方,从而形成空白。

enter image description here

如何获取它,以使消息布局位于准则的右侧,并包装其内容?

这就是我想要的:

enter image description here

,我使用wrap_width和horizo​​ntal_bias来实现

<TextView
      android:id="@+id/textview_chatmodel_message"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:background="@drawable/bubble_user"
      android:padding="8dp"
      android:text="Username: aaaaaaaa "
      android:textColor="@color/colorBlack"
      app:layout_constraintRight_toRightOf="parent"
      app:layout_constraintLeft_toRightOf="@id/guideline1"
      app:layout_constraintHorizontal_bias="1"
      android:gravity="right"/>

但是会导致不遵守Left_toRightOf guideline约束的问题:

enter image description here

如何获取它,以使消息布局位于准则的右侧,并包装其内容?

2 个答案:

答案 0 :(得分:7)

如果视图设置为wrap_content,则当其大小超过可用空间时,它将忽略约束。为了避免这种情况,您必须添加以下属性:

app:layout_constrainedWidth="true"

这是在ConstraintLayout版本1.1中添加的,在早期版本中,您需要将宽度设置为match_constraint0dp才能产生类似的行为。

  

WRAP_CONTENT : enforcing constraints (Added in 1.1)
  如果将尺寸设置为WRAP_CONTENT,则在1.1之前的版本中,它们将被视为文字尺寸,这意味着约束不会限制生成的尺寸。通常,这足够了(并且更快),但在某些情况下,您可能想使用WRAP_CONTENT,但仍要强制执行约束以限制结果尺寸。在这种情况下,您可以添加相应的属性之一:

     

app:layout_constrainedWidth=”true|false”
  app:layout_constrainedHeight=”true|false”

答案 1 :(得分:0)

一种解决方案可能是将textView包裹在一个视图组中-然后该视图组(例如,文本右对齐的相对布局)将具有与当前textView相同的约束以及0dp宽度?...我知道它需要一个额外的视图真是令人不快。