Skip to main content

Kotlin Android Basics

Introduction

Android app development with Kotlin has become the preferred approach for building modern, efficient, and reliable mobile applications. Since Google announced Kotlin as an officially supported language for Android development in 2017, its adoption has grown significantly. Kotlin offers numerous advantages over Java including concise syntax, null safety, extension functions, and full interoperability with existing Java code.

In this guide, we'll explore the fundamental concepts of Android development using Kotlin, from setting up your environment to creating your first interactive app. By the end, you'll have a solid foundation to start your journey as an Android developer.

Setting Up Your Development Environment

Before writing any code, you need to set up your development environment:

1. Install Android Studio

Android Studio is the official IDE for Android development. It includes everything you need to build Android apps.

  1. Download Android Studio from developer.android.com
  2. Follow the installation wizard instructions for your operating system
  3. Launch Android Studio once installation is complete

2. Install Required SDK Components

When you first launch Android Studio, it will guide you through setting up:

  • Android SDK: The software development kit containing libraries and tools
  • Android Emulator: For testing your apps without a physical device
  • SDK Platform-Tools: Includes adb (Android Debug Bridge) and other utilities

3. Create Your First Android Project

Let's create a simple "Hello World" project:

  1. Click "New Project" from the welcome screen
  2. Select "Empty Activity" template
  3. Configure your project:
Name: HelloKotlin
Package name: com.example.hellokotlin
Language: Kotlin
Minimum SDK: API 21: Android 5.0 (Lollipop)
  1. Click "Finish" to create your project

Understanding the Project Structure

When Android Studio finishes creating your project, you'll see a structure like this:

app/
├── manifests/
│ └── AndroidManifest.xml
├── java/
│ └── com.example.hellokotlin/
│ └── MainActivity.kt
└── res/
├── drawable/
├── layout/
│ └── activity_main.xml
├── values/
│ ├── colors.xml
│ ├── strings.xml
│ └── themes.xml
└── ...

Let's examine these key components:

AndroidManifest.xml

The manifest file describes essential information about your app to the Android system:

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

<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/Theme.HelloKotlin">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

This manifest specifies:

  • The package name (unique identifier for your app)
  • The app's components like activities
  • Required permissions
  • The minimum Android version required

MainActivity.kt

This is the entry point of your app - a Kotlin class that extends AppCompatActivity:

kotlin
package com.example.hellokotlin

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

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

The onCreate() method is called when the activity is first created. setContentView() sets the UI layout for this activity.

activity_main.xml

This XML file defines the user interface layout:

xml
<?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: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>

This layout uses ConstraintLayout (a flexible layout manager) and includes a TextView displaying "Hello World!"

Core Android Components

Android apps are built using several key components:

1. Activities

An activity represents a single screen with a user interface. Each activity is independent and can start other activities.

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

2. Layouts

Layouts define the visual structure for your UI. Android provides several layout types including:

  • ConstraintLayout: A flexible layout that positions views relative to each other
  • LinearLayout: Arranges views in a single line (horizontally or vertically)
  • RelativeLayout: Positions views relative to parent or other views
  • FrameLayout: Designed to block out an area on the screen

3. Views

Views are UI components like buttons, text fields, and images that users interact with.

Common views include:

  • TextView: Displays text
  • Button: A clickable button
  • EditText: For user input
  • ImageView: Displays images

Building an Interactive App

Let's modify our Hello World app to make it interactive. We'll create a simple counter app that increments a number when a button is clicked.

Step 1: Update the Layout

Modify activity_main.xml to include a TextView for the counter and a Button:

xml
<?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/counterTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:textSize="72sp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="@+id/incrementButton"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/incrementButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Increment"
android:padding="16dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@+id/counterTextView" />

</androidx.constraintlayout.widget.ConstraintLayout>

Step 2: Implement the Counter Logic

Update MainActivity.kt to handle button clicks:

kotlin
package com.example.hellokotlin

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView

class MainActivity : AppCompatActivity() {

private var counter = 0

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

// Find views by their IDs
val counterTextView = findViewById<TextView>(R.id.counterTextView)
val incrementButton = findViewById<Button>(R.id.incrementButton)

// Set click listener for the button
incrementButton.setOnClickListener {
// Increment counter and update the TextView
counter++
counterTextView.text = counter.toString()
}
}
}

Step 3: Run Your App

Click the "Run" button (green triangle) in Android Studio to run your app on an emulator or connected device. You'll see a screen with "0" displayed and an "Increment" button. Each time you click the button, the number will increase.

Using View Binding

The above example uses the traditional findViewById() method, but Kotlin provides better approaches. View binding is a feature that makes it easier to interact with views:

Step 1: Enable View Binding

Add to your app-level build.gradle file:

groovy
android {
// Other configurations...

buildFeatures {
viewBinding true
}
}

Click "Sync Now" when prompted.

Step 2: Update MainActivity to Use View Binding

kotlin
package com.example.hellokotlin

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.hellokotlin.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

private lateinit var binding: ActivityMainBinding
private var counter = 0

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)

binding.counterTextView.text = counter.toString()

binding.incrementButton.setOnClickListener {
counter++
binding.counterTextView.text = counter.toString()
}
}
}

View binding creates a binding class for each XML layout file, making it:

  • Safer (eliminates the risk of null pointer exceptions from invalid IDs)
  • More concise (no need for multiple findViewById calls)
  • Type-safe (all view references have the proper type)

Handling Configuration Changes

One challenge in Android development is handling configuration changes (like screen rotation). When the device configuration changes, Android typically destroys and recreates the activity.

Let's modify our counter app to preserve its state during rotation:

kotlin
class MainActivity : AppCompatActivity() {

private lateinit var binding: ActivityMainBinding
private var counter = 0

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)

// Restore the counter value if there's saved state
if (savedInstanceState != null) {
counter = savedInstanceState.getInt("counter_value", 0)
}

binding.counterTextView.text = counter.toString()

binding.incrementButton.setOnClickListener {
counter++
binding.counterTextView.text = counter.toString()
}
}

// Save the counter value when the activity might be destroyed
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt("counter_value", counter)
}
}

Now when you rotate the device, the counter value will be preserved.

Next Steps in Android Development

After mastering these basics, you might want to explore:

  1. Multiple Activities: Create apps with multiple screens
  2. RecyclerView: Display lists of data efficiently
  3. Fragments: Reusable UI components
  4. Material Design: Implement Google's design system
  5. Data Persistence: Store data using Room database
  6. Networking: Make API calls with Retrofit
  7. Coroutines: Handle asynchronous operations elegantly

Summary

In this guide, we've covered the fundamentals of Android development with Kotlin:

  • Setting up the Android development environment
  • Understanding the basic project structure
  • Creating a simple interactive app
  • Using view binding for cleaner code
  • Handling configuration changes

Android development with Kotlin offers a modern approach to building mobile applications with less code and fewer common programming errors. The combination of Kotlin's language features and Android's comprehensive framework makes it possible to create powerful apps efficiently.

Additional Resources

To continue your Android development journey:

  1. Official Android Developer Documentation
  2. Kotlin Language Documentation
  3. Google Codelabs for Android
  4. Android Kotlin Fundamentals Course

Exercises

To reinforce your learning:

  1. Modify the counter app to include a "Decrement" button that decreases the counter value
  2. Add a reset button that sets the counter back to zero
  3. Change the counter text color based on whether it's positive (green), negative (red), or zero (black)
  4. Create a simple calculator app with buttons for addition, subtraction, multiplication, and division
  5. Build a to-do list app that allows adding and removing tasks

Happy coding!



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)