I am making one of those classic layouts: an icon with two lines of text. I would like to use vector drawable for the icon, and scale it according to the text sizes. I want the top edge of the icon to line up with the top edge of the first line of text, and the bottom edge of the icon to line up with the bottom edge of the second line.
How would I do that? With ConstraintLayout!
<ImageView android:id="@+id/flower_image" android:layout_width="0dp" android:layout_height="0dp" app:layout_constraintTop_toTopOf="@+id/label" app:layout_constraintBottom_toBottomOf="@+id/text" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintDimensionRatio="1:1" app:srcCompat="@drawable/ic_flower"/> <TextView android:id="@+id/label" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintLeft_toRightOf="@+id/image" app:layout_constraintTop_toTopOf="parent" android:text="@string/flower" android:textSize="16sp"/> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintTop_toBottomOf="@+id/label" app:layout_constraintLeft_toLeftOf="@+id/label" android:text="@string/jasmine" android:textSize="24sp"/>
The width and the height of the ImageView
is 0dp
. This tells ConstraintLayout
to compute them by the constraints. In this case, the height of the ImageView
is determined by these constraints:
app:layout_constraintTop_toTopOf="@+id/label" app:layout_constraintBottom_toBottomOf="@+id/text"
The width is the same as the height.
app:layout_constraintDimensionRatio="1:1"
The rest of the constraints are for positioning.
With that, the image scales up as the text sizes increase. It stays sharp because it is a vector.
Layout Editor
I tried to make this layout with the Layout Editor, but could not figure out how to create the constraint app:layout_constraintTop_toTopOf="@+id/label"
for the ImageView
. I was hovering my cursor around the top edge but not sure how to drag it to link the two views. So I added up playing with the editor a bit to deduce the XML attributes, and switched to editing the XML directly. I hope to use the layout editor in my next attempt to use Constraint Layout.
Follow-up Twitter discussion:
@romainguy Just tried it again. Yes I can do the top & the bottom. Then I try to set the image view to 0x0 and things just go crazy.
— Chiu-Ki Chan (@chiuki) October 9, 2016
@chiuki @romainguy with 2.2, you do need to touch the XML for ratio & chains, yes
— Nicolas Roard (@camaelon) October 9, 2016
Read the whole Twitter thread.
Source code
github.com/chiuki/iconlabeltext
Click on either TextView to increase its size. Click on the image to reset.
No comments:
Post a Comment
Inline coding questions will not be answsered. Instead, ask on StackOverflow and put the link in the comment.