Starting from Scratch
As with other containers, you can create a new layout resource with a ConstraintLayout
as the root, by right-clicking over a layout
resource directory, choosing New > “Layout resource file” from the context menu, and typing in ConstraintLayout
for the root element. Fortunately, auto-complete on the “Root element” field allows you to just start typing ConstraintLayout
, then choose the fully-qualified class name from the drop-down list.
If you drag a widget into the ConstraintLayout
and drop it in an arbitrary spot, what you get at design time will be different than what you get when you run the app. In the graphical layout editor, the Button
shows up where you drop it:
However, if you look at the XML that was generated, you will see that the Button
has no constraints. It does have a pair of attributes with the tools:
prefix: tools:layout_editor_absoluteX
and tools:layout_editor_absoluteY
:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
tools:layout_editor_absoluteX="77dp"
tools:layout_editor_absoluteY="36dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
As we discussed earlier in the book, attributes in the tools:
namespace are suggestions to the development tools and have no impact on the behavior of your app when it runs. In this case, Android Studio remembers the upper-left corner of where you dropped the Button
. But, as a warning on the Button
in the layout editor will tell you, a Button
without constraints will wind up at coordinate (0,0)
at runtime (basically, upper-left for LTR languages and upper-right for RTL languages).
Dragging in a widget is insufficient. You also need to use the graphical layout editor to define the constraints, dragging the circles on the widget’s edges and connecting them to the edges of other widgets or to the ConstraintLayout
itself.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.