The CoordinatorLayout view in Android lets you create views that change their positions relative to each other. You can attach Behaviors to the children of a CoordinatorLayout that control how one view should change its properties relative to others. For example, it is the basis of the BottomSheet implementation.
While most of the magic happens in Behaviors, CoordinatorLayout itself has some layout properties you can set directly in XML. One of these, insetEdge
and dodgeInsetEdges
are quite useful but their documentation is really hard to understand. I could not get what they are for based on only the official description, only by trying them out. This short post shows you what insetEdge
can do via 3 simple screenshots.
Let’s start with our default setup, an ImageView residing in a CoordinatorLayout:
The corresponding XML code:
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/liberty" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
No surprises so far, this is just a single image. Let’s add another view at the bottom:
<TextView
android:layout_width="match_parent"
android:layout_height="200dp"
android:text="Lower content!"
android:textAlignment="center"
android:gravity="center"
android:layout_gravity="bottom"
android:background="#EF5350"/>
Notice we set layout_gravity
to bottom to indicate to Android where it should be. And the result:
Notice how it blocks the bottom part of the image. Sometimes that’s not what we want to do, we would prefer the content to be pushed up. And this is what insetEdge
does. You specify which view should be at the bottom by setting insetEdge
to bottom. This tells CoordinatorLayout that the given view should reside at the bottom and push other views up. There is an extra step needed: you have to specify for each view whether it should be pushed by the bottom view or not. This let’s you leave some views at their original places, e.g. backgrounds. So add insetEdge
and dodgeInsetEdges
to the proper views:
<ImageView
...
app:layout_dodgeInsetEdges="bottom" />
<TextView
...
app:layout_insetEdge="bottom" />
And the results:
You can see how the bottom TextView pushed the image up. Of course, this can be done with other sides of the screen as well, not only with the bottom one. Simply change bottom
everywhere to the edge you want to inset.