According to the documentation:
The index of the horizontal keyline specified to the parent CoordinatorLayout that this child should align relative to.
Can anyone explain how the 'keyline' works with an example?
According to the documentation:
The index of the horizontal keyline specified to the parent CoordinatorLayout that this child should align relative to.
Can anyone explain how the 'keyline' works with an example?
There are two parts:
CoordinatorLayout
, andFor the former, create an int array resource and reference it from the keylines
attribute of the CoordinatorLayout
. For example:
res/values/arrays.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<array name="keylines">
<item>16</item>
<item>72</item>
<item>160</item>
<item>256</item>
<item>320</item>
</array>
...
</resources>
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
app:keylines="@array/keylines"
...
Then, to position a child view horizontally relative to a keyline, set its layout_keyline
attribute to the index into the keylines
array resource. For example, to set a button on keyline 2 (position at 160dp):
activity_main.xml
...
<Button
app:layout_keyline="2"
Positioning relative to the keyline is defined by the layout_gravity
attribute. For a button, this will position the button's text, so if you want to use gravity to position the button, wrap it in another view (e.g. FrameLayout
) and set the keyline for the parent view rather than the Button
:
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|end"
app:layout_keyline="2"
...>
<Button
...
Keylines let you position a child view horizontally within a CoordinatorLayout
. The vertical positioning is determined by the vertical margins & padding and is relative to the top of the CoordinatorLayout
.
Note that if an anchor
is also set for the child view, its keyline will be ignored.
If you're curious about the layout logic, it's implemented by onLayoutChild()
and layoutChildWithKeyline()
in CoordinatorLayout
.
© 2022 - 2024 — McMap. All rights reserved.