Android Hello World Kotlin App for Beginners

Filed Under: Android

Kotlin has become the recommended and official language for android development. In this tutorial, we will learn how to create a Hello World Android app in Kotlin.

Creating Android Hello World Kotlin App

You need Android Studio and JDK version 6 or higher installed in order to build and run an android application. If you’re unaware of Android Studio do visit this tutorial before proceeding ahead.
Let’s start building our Hello World Android Application by starting Android Studio.
android hello world welcome screen

android hello world create project

The package name naming appends the application name to the reverse of the company domain name. Take note that we’ve checked Include Kotlin Support so that the default classes are originally written in Kotlin (.kt).
Set the path of the project to whatever you like! (I’ve done so for mine).

Select the Target Android Devices from the next screen. You can set the minimum SDK version as per your choice.
Following are the Android OS Versions currently available:

  • Android 1.0 and 1.1 were not publicly named.
  • Cupcake: Android 1.5
  • Donut: Android 1.6
  • Eclair: Android 2.0–2.1
  • Froyo: Android 2.2
  • Gingerbread: Android 2.3
  • Honeycomb: Android 3.0–3.2
  • Ice Cream Sandwich: Android 4.0
  • Jelly Bean: Android 4.1–4.3
  • KitKat: Android 4.4
  • Lollipop: Android 5.0–5.1
  • Marshmallow: 6.0
  • Nougat: Android 7.0
  • Oreo: Android 8.0

Choosing Activity Type

Choose the activity type from the next screen.
android add activity

Note: An Activity is whatever you see on a single screen in your application(At least on a high level that’s what it is). We’re selecting an Empty Activity right now.

You can customize the Activity name and equivalent layout file name from the next screen as shown below.
android configure activity

The layout file is typically hooked to an Activity and is used to display the UI of the activity. The layout file is written in XML.

Kotlin Android App Project Structure

Once the platform loads, the following is the project structure you should see.
android app project structure

Project Directories Contents

The core logic of our application goes inside the app module
app | src | main

  • The java folder contains the classes(ironically a kotlin class file is residing now!). To enhance the readability of the project structure you can always create a kotlin folder that keeps all the Kotlin class files.
  • The res folder contains the resources of the application. By resources we mean the following:
    • drawable: Drawable is something that can be drawn on the screen. It can be an image or a vector asset.
      In the above project structure there are two drawable folders : drawable and drawable-v24. images, vector, and SVG assets set in drawable-v24 would be used for devices with the Android API level equal to and greater than 24. In other words, if the same filename is present in both the folders, for API level above 24 the drawable-v24 file would be used.
      Alternatively, we can create different drawable folders for different screen densities. drawable-ldpi, drawable-mdpi, drawable-hdpi, drawable-xhdpi, drawable-xxhdpi are used for low, medium, high, extra high, extra extra high densities respectively.
    • layout : The layout folder contains the xml files for the views and layouts of the application.
    • mipmap: mipmap folder is specifically used to store app launcher icons. It’s similiar to drawable folder in other cases.
  • The values folder contains the following xml files:
    • styles.xml: It defines the styles and themes of the Activities and it’s subcomponents
    • colors.xml: It defines the color palettes that would eventually be used in the UI stuff
    • strings.xml: Harcoded strings are entered here. They can be accessed using the key name defined.
    • dimens.xml: We define the margins, texts and other view sizes here. Use of standard dimensions is recommended.
  • The AndroidManifest.xml file contains the essential information related to the application. The activity names, permissions, services etc all are declared here. It can easily be termed as the blueprint of the application.
  • Gradle is a general-purpose build tool. The app module’s build.gradle is a build script that contains the dependencies and plugins required in building the application. The root build.gradle contains the dependencies that are required by all modules in the project(including the app module).
  • Proguard: proguard-rules.pro files resides in the root of the project. It is used for two primary purposes:
    • Shrinking of Code and Resources to minimize the APK size: Code shrinking is available with ProGuard, which detects and removes unused classes, fields, methods, and attributes from your app, including those from included libraries. We can specify rules inside the proguard-rules file specific to each build variant. In all, it optimises the bytecode and removes the unused resources
    • Code Obfuscation: Proguard helps in obfuscating your code thus make your code difficult to reverse engineer and hence makes it secure.

The androidTest and test folders should contain the code for unit testing the application.

Difference between androidTest and test folders

The androidTest folder contains the unit testing code related to Android Framework.
The test folder contains unit testing code involving pure java/kotlin classes.

Android Hello World Kotlin Code

Let’s look at what the layout file i.e. activity_main.xml looks like:

<?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="net.androidly.helloworldkotlin.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" />

</android.support.constraint.ConstraintLayout>

ConstraintLayout acts as a parent view inside which we can place subviews relative to the constraint positions of each other. We’ll go into its details in a later tutorial.

TextView is a view that displays a string.

The above XML is displayed in the text editor of the layout file.
We can also view and arrange our UI from the design editor that’s given below.

android app layout design

We’ve added a button to the above layout by dragging it from the sidebar. We’ve fixed the constraints such that it is positioned below the TextView. Don’t worry if these things are going over your head right now. We’ll cover each of these stuff separately in our later tutorials.

Let’s look at the MainActivity.kt file as shown below.

package net.androidly.helloworldkotlin

import android.support.v7.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {

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

In Kotlin classes are public and final by default, so specifying the keyword class would suffice.

Note: To specify a class as not final we need to mention it as open.

Unlike Java, Kotlin doesn’t have an extends keyword. A colon is used instead.

AppCompatActivity is derived from the Activity class and it supports backward compatibility.

This allows the current code to work on devices with older Android devices.

AppCompatActivity enables the use of ActionBar and other Material Design specific implementations like the Toolbar etc.

In Kotlin a function is defined using the keyword fun.

The onCreate function is where the Activity loads onto the screen and displays the layout by invoking the function setContentView with the layout file.

Note: R.java file is an auto-generated file that contains resource IDs for all the resources present in the res folder.

Linking Views From Layout to Activity

Did you notice we’d set an id to our TextView and Button present in the activity_main.xml layout file?
We’ll use the very same to access them in our Kotlin Activity class.

Unlike Activities in Java, Kotlin Activity class does not require a findViewById method to bind the views in the activity. To access the layout elements in the Kotlin activity we need to add the following import line at the top:

import kotlinx.android.synthetic.main.activity_main.*

We’ve added a feature that changes the text present in the TextView when the Button is clicked as shown below:

package net.androidly.helloworldkotlin

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

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

        button.setOnClickListener { textView.setText("Hello World With Kotlin") }
    }
}

This looks a lot cleaner, concise than its Java Equivalent as shown below:

public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView = findViewById(R.id.textView);
        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView.setText("Hello World with Kotlin is better");
            }
        });
    }
}

In the Kotlin code, there’s no need to declare the views or override the onClick method interface. Furthermore, no semicolons required!

Running Our Hello World App

We can either run the application on a USB connected device or on an emulator. Click on the run button from the toolbar and you’ll be shown a window to choose the device you wish to run on:
android app select deployment

Create a Virtual Device if you haven’t. Once it’s ready the project would build and run on your device.
Following is the output of our application when running on a device.
android hello world kotlin app output

To enable USB Debugging on your smartphone:
Settings > About Phone.
Tab Build Number 7 times to activate Developer mode.
You’ll be able to find Developer Options in your settings. Go ahead and enable USB debugging from there.

This brings an end to this tutorial. You can download the Android Hello World Kotlin Project from the link below.
Stay tuned as we have lots to cover in our Android Development with Kotlin series.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages