Have you ever wanted to build an Android app but couldn't figure out where to start? In this tutorial, I will show you how to use Android Studio to build your first ever Android app.
Android Studio is based onIntelliJ, an IDE (Integrated Development Environment) developed byJetBrains. It is very powerful and helps you manage your development workflow via shortcuts, method generation, automated code refactoring, direct links to the various parts of your project, Javadoc popups, and so on. Google designed Android Studio for Android development, with support for XML (with a convenient WYSIWYG editor) and Groovy (for Gradle scripts). It also offers a feature-rich emulator where you can push code and resource changes to your running app without the need of restarting it.
The app we are creating won't do anything fancy. It will be just a simple "Hello, World" app that will greet you when you click a button. The aim here is to get your feet wet and help you get started without being overwhelmed.
Setting Up the Project
You will have to set up a bunch of things before we can start creating the actual app. The first step is to download and install Android Studio. Run the program once it has finished installing and you will see the following screen. Click on the New Project button.
You will now see a screen with different device types listed on the left and a bunch of options on the right. The options on the right are actually activity templates which create some boilerplate code for you to quickly get started. Select Phone and Tablet on the left and Empty Activity on the right. After that, hit the Next button. Selecting Empty Activity will create a single layout file and an empty activity.
You will be asked to provide an app name and a package name on the next screen. We will set the app name to Hello World and the package name to com.tutsplus.helloworld. Specify a project directory and choose Kotlin as your language.
The app name is what the users will see once they install your application. This can be same for multiple apps. For example, more than one person can create a calculator and name the app Calculator. The package name on the other hand has to be unique so its name is somewhat weird. The com.tutsplus part in the package name is simply an easy way to ensure uniqueness because domain names are unique for different organizations and companies etc.
The Android SDK is in continuous development and every year a new version is released with all sorts of improvements and new features. Some tools and libraries that you can use in later Android versions are not present in older ones. Google's support libraries bring some of the new features to older versions of the Android operating system, such as material design elements. The support libraries can only do so much, though.
We are setting our API level here to 21 which will cover around 98% of the devices at the time of writing this tutorial. You can go even lower to support more devices. Now click on the Finish button and Android Studio will set everything up for you. This includes creating appropriate directories and files.
Understanding the Project Structure
As I mentioned earlier, Android Studio will create a bunch of files and directories for you based on the options you provided in the previous section.
On the left, you should see a tree of directories. That is the heart of your project where you can find the files and assets of your project. The folders you'll spend most of your time in are java and res. In java, you find your project's code files for adding functionality. In res, you can find the rest of your project's resources, such as layouts, values sheets, images, and so on.
The two files that we will be modifying here are: MainActivity.kt and activity_main.xml. The MainActivity.kt file should be under app > java > com.tutsplus.helloworld > MainActivity.kt as shown in the image above. Similarly, the activity_main.xml file should be under app > res > layout > activity_main.xml. The former will contain our programming logic while the latter will handle the layout.
There are a bunch of tiny buttons on the top-right side of the Android Studio. These buttons give you easy access to important functionality like running, debugging, profiling or stopping an app. You will also find the device manager here. It is used to manage virtual and physical devices where your app would run.
Creating the App Layout
Android Studio comes with a fantastic and beginner friendly layout editor. When first starting out, you will find that it is easier to create a layout using the editor instead of writing code. However, I would recommend that you start directly working with the xml code in the layout file as you become more comfortable with the tool. We will stick with the visual editor for our first app.
Click on the activity_main.xml tab in your workspace if the file is already open or open it by going to app > res > layout > activity_main.xml in the project window.
It is easier to work with the layout editor if it is taking up a larger share of the screen real estate. You might want to hide the project window by clicking on the Project tab on the left edge of the workspace. Also make sure that you have selected the Design tab visible in the top-right part of the layout editor. This should give you something similar to the image below.
Right now, you are seeing two different surfaces of the layout. One is the Design view and the other is the Blueprint view. The design view makes it easier to see what our layout looks like. I find the blueprint view more helpful when creating the layouts because it reduces unnecessary clutter. You won't notice much of a difference unless you are working on some complicated layouts.
You can click on the light blue button in the image to select a design surface. We will be setting it to Blueprint for our tutorial. You can also cycle through all the options by pressing the B key.
The layout should already have a TextView
element. Set its attribute values as shown in the image below. The id
attribute is used to get a reference to the element within our code. The gravity
attribute has been set to center
to keep the text in the center. The textSize
attribute is set to 24sp
. Change the value of text
attribute to Hello, anonymous!
. This is what the users will be see when they first open the app. This element has been constrained to the parent element.
Now drag a Button and a Plain Text element from the palette and set their attribute values as shown in the images below.
We will begin with the Button and set its id
attribute to button. The top and right margins of the button have been set to 40dp and 16dp respectively. The right margin is denoted by the layout_marginEnd
attribute. The value of the onClick
attribute determines the function that would be called upon clicking the button. We have set it to greetPeople
. Don't worry about the red outline around the value. This will go away when we define our function later.
For the Plain Text element, the input
type is set to textPersonName|textCapWords
. Using textCapWords
will tell the device to auto-capitalize the first and last name of the user. The top and left margins of the button have been set to 40dp and 16dp respectively. The end (right edge) of our input has been constrained to the start (left edge) of our button.
The actual dimension and positions of different elements in a layout also depend on the constraints that you want to enforce.
Click on the Code tab in the layout editor and you will see that Android Studio has translated our design to the following XML code.
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/main_layout" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"><TextView android:id="@+id/greeting" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:text="Hello, anonymous!" android:textSize="24sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /><Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="40dp" android:layout_marginEnd="16dp" android:onClick="greetPeople" android:text="Greet Me" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" /><EditText android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="40dp" android:layout_marginEnd="16dp" android:ems="10" android:inputType="textPersonName|textCapWords" android:text="Name" app:layout_constraintEnd_toStartOf="@+id/button" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /></androidx.constraintlayout.widget.ConstraintLayout>
Switch back to the Design tab and change the surface from Blueprint to Design. You should see something similar to the image below.
Writing the Code
In the previous section we set the value of onClick
attribute for our button to greetPeople
. So we will now define a function called greetPeople()
inside our MainActivity.kt file.
The function will basically get a reference to both the text input as well as the text view. The value from the text input will be concatenated to the string Hello and assigned as a value to the text view.
fun greetPeople(view: View) { val personNameInput = findViewById<EditText>(R.id.name) val greetingTextBox = findViewById<TextView>(R.id.greeting) val personName = personNameInput.text.toString() val greetingString = "Hello, $personName!" greetingTextBox.text = greetingString }
You will also have to do a few imports for EditText
, TextView
and View
to avoid reference errors. The whole code for the file MainActivity.kt should be as shown below.
package com.tutsplus.helloworld import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.EditText import android.widget.TextView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } fun greetPeople(view: View) { val personNameInput = findViewById<EditText>(R.id.name) val greetingTextBox = findViewById<TextView>(R.id.greeting) val personName = personNameInput.text.toString() val greetingString = "Hello, $personName!" greetingTextBox.text = greetingString } }
Running the Android App
Now it is time to finally run our app. You can either run it within the emulator on a virtual device or you can install it on a physical device. Click on the Create Device button under Device Manager to create your virtual device. Pick a device name on the next screen. I went ahead with Pixel 2. You can use something else if you want.
Click Next and install a system image. I picked Android R here.
Creating the virtual device will take some time. After that, you can either click the Run App button or press Shift + F10. The app will now run on the emulator. Enter your name in the text input and click on Greet Me. You should get something similar to the image below where I have included screenshots from the emulator and a physical device side-by-side.
Final Thoughts
That's it! We successfully created and ran our First Android app in Android Studio. You can now start experimenting with the layout or the code to make tiny alterations. This will help you gain more familiarity with Android Studio and learn some new things. For example, you could try to place the button below the text input or add a new button to show another greeting.