4

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?

Allan Veloso
  • 5,823
  • 1
  • 38
  • 36
Nilesh Rathore
  • 886
  • 1
  • 12
  • 22
  • 1
    Couldn't find how it works in CoordinatorLayout, but for an explanation of what keylines are for there is this link: https://material.io/design/layout/spacing-methods.html#spacing – Allan Veloso Mar 12 '19 at 20:34

1 Answers1

0

There are two parts:

  1. setting the keylines for the CoordinatorLayout, and
  2. referencing a keyline in a child view.

For 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.

outis
  • 75,655
  • 22
  • 151
  • 221