Constraint layout with percentage not working as expected
I would make a view that is 70% wide and aligned to the right of its parent using layout constraints as follows
<android.support.constraint.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="wrap_content"
>
<android.support.constraint.Guideline
android:id="@+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.3"/>
<TextView
android:layout_width="match_parent"
android:layout_height="40dp"
android:text="Hello text"
app:layout_constraintLeft_toRightOf="@+id/guideline"
app:layout_constraintRight_toRightOf="parent"/>
</android.support.constraint.ConstraintLayout>
The TextView always occupies the full parent width. Any idea what I am doing wrong?
+3
source to share
1 answer
Two minor but important changes:
- TextView width must be 0dp ie match constraint and not match parent
- Leadership orientation should be vertical, not horizontal.
Here's the code:
<?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">
<android.support.constraint.Guideline
android:id="@+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.3" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Hello text"
app:layout_constraintLeft_toRightOf="@id/guideline"
app:layout_constraintRight_toRightOf="parent" />
</android.support.constraint.ConstraintLayout>
Output:
Also note that I changed the height of the ConstraintLayout to match_parent so that the guide is visible in the output. You can change it back to wrap_content.
+6
source to share