ConstraintLayout Practice Tips – Follow layout
demand
Sometimes the UI might want something like this: the title on the left is of variable length, followed by a label. Depending on the length of the title, it can have the following styles:
① The title is longer than one line
② The title has no content
③ The title is less than one line
The specific effect is shown below
implementation
Instead of ConstraintLayout, we use a RelativeLayout, LinearLayout, and so on. We’ll find it difficult to do, or we’ll find it difficult to do.
It’s lucky we have ConstraintLayout.
How do I write that? The core is to first string elements into a chain and select Packed as the style of the chain. This is not enough. At the same time set the following two properties for the first element:
app:layout_constrainedWidth="true"
app:layout_constraintHorizontal_bias="0"
Copy the code
Finished, the specific code is as follows:
<android.support.constraint.ConstraintLayout
android:id="@+id/cl"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="10dp"
android:background="#eee"
android:paddingLeft="10dp"
android:paddingRight="10dp"
app:layout_constraintTop_toBottomOf="@id/tv_desc">
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:gravity="center"
android:maxLines="1"
android:text="I am text I am text I am text I am text I am text I am text I am text"
android:textColor="#FDA413"
android:textSize="12sp"
app:layout_constrainedWidth="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0"
app:layout_constraintHorizontal_chainStyle="packed"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toLeftOf="@id/iv"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:src="@drawable/icon_birthday_cake"
android:visibility="visible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toRightOf="@id/tv"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:visibility="visible" />
</android.support.constraint.ConstraintLayout>
Copy the code