Create a first Android application

C

The purpose of this tutorial is to learn how to create a project in Android Studio. You will learn how to configure project for the phone and the tablet – create different layout files to portrait and landscape mode and how to use resources to support different languages and localisation. Created application will be tested with Android Studio emulators and/or with own device. In conclusion, this tutorial will give you good start to Android application development.

Android Studio

Android Studio is Android’s official IDE. It is purpose-built for Android to accelerate your development and help you build the highest-quality apps for every Android device. It is available for download on Windows, macOS and Linux based operating systems.

Go to Android Developer site, download and install Android Studio.

After that, you are ready to start your Android application development.

Create a new Android Studio project

Launch Android Studio and start a new Android Studio project. In the Welcome to Android Studio window, click Start a new Android Studio project.

In addition, you can open an existing Android Studio project, check out project from Version Control, or import other projects.

Choose your project template

Now you are creating your first Android Project, select an Empty Activity as a project starting point. This template generates activity class and activity layout files for you project. This template is one of the smallest template, which is available. That’s why it is nice starting point to create a first Android Application.

In addition, you can select many different templates to start work with.

Configure project

Next you will see the the Configure your project dialog.

  • Type First Application in the Name field.
  • After that, type com.example.firstapplication in the Package name field. Package name need to be unique, if you are going to publish app to Google Play. You can use your own domain name here.
  • Select your project location folder.
  • Select Kotlin from the Language drop-down menu.
  • Make a selection from the Minimum API level. Android Studio will give an estimate how many devices can install your application. Click Help me choose link to learn more.

Click Finish and after some processing time, the Android Studio main window appears.

Explore project

AndroidManifest.xml

The manifest file describes the fundamental characteristics of the app and defines each of its components. Every app project must have an AndroidManifest.xml file (with precisely that name) at the root of the project source set. The manifest file describes essential information about your app to the Android build tools, the Android operating system, and Google Play. Therefore, it is one of the main files in your project.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="fi.ptm.firstapplication">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

Defined MainActivity will be launched, when application is started. Action MAIN and category LAUNCHER is used to give this information to system.

MainActivity

This is the main activity of your application. It’s the entry point for the app. When you build and run your app, the system launches an instance of this Activity and loads it’s layout, when onCreate function will be called. This method receives the parameter savedInstanceState, which is a Bundle object containing the activity’s previously saved state. This Bundle is used to save instance state at the running time. The value of the Bundle object is null, if the activity has never existed before. However, it is not used at this time.

package fi.ptm.firstapplication

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // layout will be drawn to the screen from activity_main.xml file
        setContentView(R.layout.activity_main)
    }

}

activity_main.xml

This XML file defines the layout for the activity’s user interface. It contains now a TextView element with the “Hello, World!” text by default. In other words, it is quite empty.

<?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_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Add android:id="@+id/textView" attribute in TextView element. You will add programming later and this id will be used to change text in this TextView.

build.gradle

There are two files with this same name: one for the project, Project: First Application, and one for the app module, Module: app. Each module has it’s own build.gradle file, now this project currently has just one module. You can use each module’s build.file to control how the Gradle plugin builds your app. However, it is not important in this first tutorial.

Usually developer only need to modify Module: app file. One use case is to add dependencies to 3rd party libraries or change versionCode and versionName attributes. For instance, when app is published to Google Play.

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "fi.ptm.firstapplication"
        minSdkVersion 28
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.core:core-ktx:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}

Create a new Android Virtual Device

Application project and settings are now generated. Now it can be build and run. You need to create an Android Virtual Device or use your own device connected to computer. After that, you can run your application.

  • Select Tools > AVD Manager and create a new Virtual Device

You can create different Android devices like TV, Phones, Tables and Wears with multiple different configurations. Now, it is enough to create a just one Phone AVD for a testing purposes.

  • Select Phone and Nexus 5X with Google Play support and click Next

In the next dialog, you will need to select which API version is installed to your AVD. Select the API version what you want to use a testing. You might need to download the image first.

Remember that, you can create different AVD’s with different API configuration to test your application in different API versions and devices.

Use API level in your AVD name and you will remember it’s contents better. Click finish and AVD will be created.

Build and run your first Android application

Now you are ready to test your application in AVD or connected phone/tablet. Connect your device to your development computer with a USB cable. If you developed on Windows, you might need to install the appropriate USB driver for your device.

  • In Android Studio, select your app from the run/debug configurations drop-down menu in the toolbar.
  • In the toolbar, select the device that you want to run your app on from the target device drop-down menu.
  • After that, click Run button and your app will be build and run

Android Studio installs your app on your connected device and starts it. You should now see “Hello, World!” text displayed in the app on your device. In other words, your application is working nicely.

Add strings to String resources

It is good to separate string values from the code and UI. This way Android resources can be used to make multi language support for application. In other words, you need to do as many strings.xml files as many languages you want to support.

  • Open strings.xml from app > res > values folder
  • After that, add a below string values
<resources>
    <string name="app_name">First Application</string>
    <string name="button_txt">Click Me!</string>
</resources>

A new string values can be added to strings.xml by typing directly (like you did) or use Translation Editor. Click “Open Editor” text link to open Translation Editor.

Add a new string resource:

  • Key: button_clicked_txt
  • Default Value: Button Clicked!

In conclusion, a new string value will be added and it can be used from code or UI. Read more information here: String resources.

Modify MainActivity layout

Next you are going to add one button to the layout. The default layout contains a TextView, which displays “Hello World” text. Now you can use that same TextView to show some text. However, usually you are going to do a new views for all of your items.

  • Drag and drop one Button to layout above TextView
  • After that, use Constraint layout “hotspots” and center button horizontally. Layout it above TextView and use for example 40 units.
  • Modify Button text to load from string resources @string/button_txt
  • Add onClick method: buttonClicked

Similarly, you can modify your XML code directly and add buttonClickedmethod.

Button onClick event handling

MainActivity will load activity_main layout, when application is launched with onCreate method. This layout contains our Button, so buttonClicked function need to declared here.

  • Open MainActivity from App > java > com.example.firstapplication folder.
  • Add buttonClicked function to display text from String resources.
package fi.ptm.firstapplication

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
// import View class
import android.view.View
// import all id's from activity_main layout (now only textView is used)
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // layout will be drawn to the screen from activity_main.xml file
        setContentView(R.layout.activity_main)
    }

    // View class need to be used in parameter, even it is not used
    fun buttonClicked(view: View) {
        // activity_main layout has textView id in TextView element
        textView.setText(R.string.button_clicked_txt)
    }
}
;

You will get a few unresolved references: View and textView. You need to import those classes. After that, they should work.

Run and test

Now application should work. You can test it in real device or emulator. In other words, button event handling is now working.

Localization

Now application uses only English language defined in string resources. To support different languages, you need to create additional string.xml (or other resource files like style or values) to application resources. Read more information here: Localization and Localize the UI with Translations Editor.

  • Open your strings.xml file.
  • After that, click “Open editor” text at the right top corner of opened file.
  • Translation Editor should be visible.
  • Click small earth button to add a new language.
  • Browse and select Finnish (fi).
  • Add a Finnish to Finnish (fi) section

You should have two strings.xml files in your values folder (default and for the Finnish). In other words, they will be used automatically from the resources by the Android system.

  • Go to your device settings and after that, switch your AVD to use a previously used language and start your application again. Remember you need to run/install app again.

Now you application should be in Finnish. Localisation is done by using resources. In other words, they will be automatically loaded by the system.

Orientation

Android can load application layout files directly from the application resources. Now application contains only one layout: activity_main.xml, which is stored to layout folder. This same layout file will be used, if an application is portrait or landscape mode. You can create a separate layout file, which will be used, if device is landscape. Look more information here: App resources overview and Build a UI with Layout Editor.

  • Add a new string elements to string resources: directly from code or use Translation Editor.
<resources>
    <string name="app_name">First Application</string>
    <string name="button_txt">Click Me!</string>
    <string name="button_clicked_txt">Button clicked!</string>
    <string name="portrait_txt">Portrait orientation</string>
    <string name="landscape_txt">Landscape orientation</string>
</resources>
  • After that, add one TextView to activity_main.xml layout.
  • Position it at the bottom and middle.
  • Use portrait_txt string resource in above TextView.
  • Open activity_main.xml layout if it is not open and visible in designer.
  • After that, click Screen orientation and layout variants -button in designer (it is second button above design view) and select “Create Landscape Variation”.

This will generate a new layout file to your project (look your app > res > values > layout folder).

  • Modify generated layout’s TextView use landscape_txt.
  • After that, run application and switch orientation to portrait/landscape using Rotate Left/Right buttons in AVD.
  • if layout not switch automatically, click a small “arrow” button near “square”, “circle” and “triangle” buttons in emulator. After that, your layout should switch automatically.

Test

Nice, you can create different layouts for the portrait and the landscape orientation and those will be loaded automatically from the application resources like localization.

code

Check project from GitLab – Create a first Android Application

Add comment

Pasi Manninen

Pasi Manninen

Pasi is a mobile and web application developer. Currently working as a senior lecturer in JAMK University of Applied Sciences. Pasi has programming experience over many decades and has taught dozens of courses since the 90's.

Recent Posts

Follow Me