Adding elements to your android layout is a core part of the app development process. Luckily it’s pretty easy to do once you’ve downloaded Android Studio.
Locate the Layout File in “res” folder
The res folder contains your resources, of which, your layouts are one of them. Start by expanding the res folder in the project explorer.
If you don’t have the buttons on the side, the project explorer is easily toggled using Alt+1.
Open the activity_main.xml file
In the layout file you’ll have a bunch of xml. This code describes the widgets, containers and their positioning. Similar to HTML.
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.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="com.truemiller.test21.MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout>
If you don’t see XML, but instead see a “drag and drop” GUI, there are two tabs at the bottom where you can switch between the two views.
Note that the design view creates code in the text view, and vice-versa.
Adding Elements with Code First…
Android is studio is really helpful in that it will offer code completion.
If you press Enter on this example Button option, then it’ll generate some attributes for you automatically.
You’ll then be asked to fill in the default attributes, and are again offered auto-completion.
Adding Elements using the Design tab..
The design tab is great for quickly generating layouts, as you can drag and drop elements onto the layout.
Additionally, you can also see the default palette of elements that can actually be added. If you’re a learner this is super handy.
Below the pallette there’s a component tree where you can directly edit and manipulate your layout’s elements.
That’s all for adding elements to an android layout.
Until next time,