Computer scienceMobileAndroidUser InterfaceResources

XML Layouts

11 minutes read

XML (eXtensible Markup Language) is a text-based format for storing and structuring data. It is extremely popular because it is very comprehensible for people and machines alike.

In this topic, we will discuss Android layouts, why we need them, and how to use them properly.

What are layouts?

Layouts in Android are used to define the application user interface (UI). Simply put, a layout is a visual template for your application screen that lets you control the properties and positions of your elements. They are stored as XML files and located in the folder res/layout, which can be found in your Project folder.

Creating layouts in XML files helps you separate your UI from your code. Every layout file should contain only one root element which must be either a View or a ViewGroup object. Inside the root object, you can add as many elements as you need to create the UI of your future app.

View objects are simple blocks that respond to the user's actions. For example, Button responds to a click, EditText allows you to input some text, Switch allows you to choose between two states, and so on.

ViewGroup is a special View that can contain other Views. It is the base class for Layouts in Android. In other words, ViewGroup acts as an invisible container for the View objects. For example, your Layout (like LinearLayout or FrameLayout) is the ViewGroup that contains TextView, which is a View object.

You will learn more about View and ViewGroup in the upcoming topics.

Creating and building XML layout

Usually, when you create a new project, Android Studio automatically generates a new layout for you. If it doesn't happen, right click on res/layout in your Project Structure, choose New > Layout Resource File, and then double-click your new .xml file. A Layout Editor should pop up displaying a blank page. If you opened a file which has already been generated with the project, you will see this:

XML Layout Editor Design View

Layout Editor lets you easily build XML layouts in the visual editor instead of writing them by hand. It allows you to immediately see how your UI will look on different screen sizes or in different Android versions.

To start building your UI, select something from the Palette and drag it into your layout. You will see this element in your layout; it will also pop up in the Component Tree located under the Palette.

Tip: You can open reference documentation for an element by selecting it in the Palette and pushing Shift + F1 on Windows and Shift + Control + F1 on Mac.

To move your View element or change its attributes, choose it in your layout preview or find it in your Component Tree. On the right side are some basic and commonly used attributes. In this window, you can quickly set the element's ID, set constraints, and change the text. To see the full list, click "All attributes".

Even though Android Studio offers a very powerful Layout Editor, in some situations it's faster to write code manually. To quickly switch the current View mode, just press "Code" or "Split" in the upper right corner of the Layout Editor. In this mode, you will see everything you've built with the visual editor as if you've written it by hand.

Connect your XML with the Activity

When you compile your app, all layouts are compiled into layout resources. When you launch your app, the function onCreate() can apply your XML file to the Activity by calling setContentView(). To pair XML with your Activity, type its name in the function setContentView(R.layout.XML_FILENAME).

For a layout activity_main.xml, it should look like this:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
}

Note that you do not need to specify the exact file extension.

That's it! Now, when you run your app you will see everything you've built in your layout.

Attributes

Every View subclass supports its own attributes. Attributes can be specific (for example, hint in EditText) or common (like ID, layout parameters, etc.). Here is an example of a standard XML layout generated by Android Studio:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

The first line is called an XML prolog. Keep in mind two important things about the prolog: it must be the first line of the document, and it must not have a closing tag.

After the prolog line, we have the layout's root object. In this case, it's ConstraintLayout, a ViewGroup object. There are different types of layouts: RelativeLayout, LinearLayout, but don't think about them right now: you will learn more about Layout types in the next topics. Don't forget that all objects except the prolog must be closed.

In the next three lines, we have xmlns which declares an XML namespace. Namespaces are used to get rid of tag name conflicts in XML files. In this case, we have android, app, and tools.

  • xmlns:android namespace is used to access attributes that are provided by the Android platform. For example, you should use android namespace if you need to give some element an ID, set text to TextView, or change width or height.

  • xmlns:tools is used to display UI elements only for viewing in the design mode and will not affect your built app.

  • xmlns:app is used to access custom attributes defined in your app, by your code, or by libraries you import: in other words, attributes not defined by the Android.

Inside the root object ConstraintLayout you can place any View object. In this case, we have a TextView with several simple attributes: ID, width, height, and text to display. ID's are used to find your element and interact with it.

Important: Try to keep your View ID as unique as possible.

The last four attributes define TextView position on the screen. Right now, they are set to place the text "Hello World!" in the middle of the screen.

Editing XML by hand

We've learned how to use the Layout Editor. Now, let's try to create a Button by coding it manually. In your XML layout file, find the end of the tag of your View.

When you start typing <Button, Android Studio will give you a few options to choose from. Select Button and hit enter. Studio will automatically add attributes like layout_width and layout_height. Choose match_parent and your button will fill all the available space, or choose wrap_content and let it adapt to the text. If you're in the "Code" View mode, switch to "Split". You should see a blank button on your layout.

The button looks rather plain and confusing: we should probably add some text. Hit "Enter/Return" after your last attribute and then type text. IDE's autocomplete will offer you to choose the android:text attribute, which is exactly what we need. Enter any text between the quotation marks and you will see it in the layout's preview.

Do not forget about the ID: type "id" and use the suggested android:id attribute. Inside the quotation marks, type @+id and specify a simple ID for this button.

The last thing you need to do is close the tag. Press the slash button "/" and Android Studio will do it for you.

Conclusion

Congratulations on making your first steps in Layouts and Android app UI! Whether you like creating your UI in Visual Editor or writing everything by yourself, you have the necessary knowledge and skills to do it with confidence. Now challenge yourself and put your skills into practice!

160 learners liked this piece of theory. 6 didn't like it. What about you?
Report a typo