Using Widgets and Containers from Libraries

In an earlier chapter, we saw that layout resources use XML elements to describe the UI. The elements that we explored — TextView and Button — had simple element names, plus attributes that were prefixed with android:. This is how you will use most of the widgets and containers that are part of the “framework classes” — the classes that are part of Android itself and ship with Android devices.

However, ConstraintLayout is from a library, so it is not part of the framework classes. A copy of the code for ConstraintLayout is packaged in your APK and ships with your app.

Using widgets and containers from libraries is very similar to using widgets and containers from the framework classes, with two key differences.

Fully-Qualified Class Name

In the chapter on widgets, we focused on TextView and Button. Those widgets have XML elements named <TextView> and <Button>, respectively.

Most framework widgets work that way: the XML element can be the bare class name. No library widgets work that way. For those, the XML element needs to be the fully-qualified class name. So, when using ConstraintLayout, you will see XML elements like <androidx.constraintlayout.widget.ConstraintLayout>. This gets a bit wordy if you are working with the XML, but if you are mostly using the drag-and-drop GUI builder, you will barely notice the difference.

app: Attributes

You will also find that some of the XML attributes do not get the android: prefix, but instead get an app: prefix. These are XML attributes defined by the library code, whereas android:-prefixed attributes come from framework code.

This means that the first time you start using library widgets and containers in a layout resource, you might see app show up in red:

Android Studio Layout XML Editor, Showing Red app
Android Studio Layout XML Editor, Showing Red app

This means that the app XML namespace has not been declared. The simplest way to add it is to:

Android Studio Layout XML Editor, Showing Quick-Fix Menu
Android Studio Layout XML Editor, Showing Quick-Fix Menu

This will add xmlns:app="http://schemas.android.com/apk/res-auto" to your root XML element of the layout resource.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.