cyberangles guide

How to Build Your First Android App with Kotlin

Android powers over 70% of the global smartphone market, making it an incredibly popular platform for app development. If you’ve ever dreamed of creating your own mobile app—whether it’s a simple tool, a game, or a productivity helper—now is the perfect time to start. Kotlin, Google’s preferred language for Android development, is concise, safe, and interoperable with Java, making it ideal for beginners and experts alike. In this step-by-step guide, we’ll walk you through building your first Android app with Kotlin. You’ll learn how to set up your development environment, design a user interface (UI), add functionality with Kotlin code, test your app, and even explore next steps like publishing to the Google Play Store. By the end, you’ll have a working app and the foundational skills to build more complex projects.

Table of Contents

  1. Setting Up Your Development Environment
  2. Understanding the Android Project Structure
  3. Designing the User Interface (UI)
  4. Adding Functionality with Kotlin
  5. Testing Your App
  6. Enhancing Your App (Optional)
  7. Publishing to Google Play (Overview)
  8. Conclusion
  9. References

1. Setting Up Your Development Environment

Before writing a single line of code, you’ll need to set up Android Studio—the official IDE for Android development. It includes everything you need: a code editor, emulator, SDK tools, and Kotlin support.

Step 1: Download Android Studio

  • Go to the Android Studio download page.
  • Select the version for your operating system (Windows, macOS, or Linux) and follow the installation prompts.

Step 2: Install and Configure Android Studio

  • During installation, accept the default settings (including the Android SDK, which provides tools and libraries for app development).
  • On first launch, Android Studio may prompt you to install additional components (e.g., the latest SDK platform). Click Install to proceed.

Step 3: Set Up an Emulator or Physical Device

To test your app, you’ll need either:

  • An Android Emulator: A virtual device that runs on your computer.
  • A Physical Android Device: Connect your phone via USB (enable “USB Debugging” in Settings > About Phone > Tap “Build Number” 7 times to unlock Developer Options, then enable USB Debugging).

Creating an Emulator (AVD)

  1. Open Android Studio and click Configure > AVD Manager (or go to Tools > AVD Manager).
  2. Click Create Virtual Device.
  3. Select a device model (e.g., “Pixel 7”) and a system image (choose the latest stable Android version, like “Android 14 (API 34)”).
  4. Follow the prompts to finish setup. Your emulator will now appear in the AVD Manager.

2. Understanding the Android Project Structure

Once Android Studio is set up, let’s create a new project and explore its structure.

Step 1: Create a New Project

  1. Open Android Studio and click New Project.
  2. Select the Empty Activity template (a basic starting point) and click Next.
  3. Configure your project:
    • Name: Enter your app name (e.g., “FirstKotlinApp”).
    • Package Name: A unique identifier (e.g., com.yourname.firstkotlinapp).
    • Save Location: Choose where to store the project.
    • Language: Select Kotlin.
    • Minimum SDK: Choose the lowest Android version your app will support (e.g., “API 24: Android 7.0 (Nougat)” for broad compatibility).
  4. Click Finish. Android Studio will generate the project files.

Key Project Folders and Files

Your project will have a folder structure like this (focus on the app module, which contains your app’s code):

app/  
├── src/  
│   ├── main/  
│   │   ├── java/[package]/  # Kotlin source code (e.g., MainActivity.kt)  
│   │   ├── res/             # Resources (layouts, strings, images, etc.)  
│   │   │   ├── layout/      # UI layouts (e.g., activity_main.xml)  
│   │   │   ├── values/      # Strings, colors, styles (e.g., strings.xml)  
│   │   │   └── ...  
│   │   └── AndroidManifest.xml  # App configuration (permissions, activities)  
│   └── ...  
└── build.gradle  # Build settings (dependencies, SDK versions)  
  • MainActivity.kt: The main Kotlin file where your app’s logic lives. An “Activity” is a screen in your app.
  • activity_main.xml: The layout file that defines the UI for MainActivity.
  • AndroidManifest.xml: Declares app components (like activities) and permissions (e.g., internet access).

3. Designing the User Interface (UI)

The UI is what users see and interact with. We’ll design a simple screen with:

  • An input field (EditText) for the user to enter their name.
  • A button (Button) to submit the input.
  • A text view (TextView) to display a greeting.

Using the Layout Editor

Android Studio’s Layout Editor lets you design UIs visually or via XML. We’ll use XML for precision (though the visual editor is great for previewing).

Step 1: Edit activity_main.xml

Open res/layout/activity_main.xml. By default, it uses ConstraintLayout—a flexible layout that lets you position elements relative to each other.

Replace the Default XML with This Code:

<?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">  

    <!-- EditText: For user input -->  
    <EditText  
        android:id="@+id/nameEditText"  
        android:layout_width="0dp"  <!-- Match constraints (full width) -->  
        android:layout_height="wrap_content"  
        android:hint="@string/name_hint"  <!-- Hint text (from strings.xml) -->  
        android:inputType="textPersonName"  
        app:layout_constraintEnd_toEndOf="parent"  
        app:layout_constraintStart_toStartOf="parent"  
        app:layout_constraintTop_toTopOf="parent"  
        app:layout_constraintMarginTop="32dp"/>  <!-- Margin from top -->  

    <!-- Button: Triggers the greeting -->  
    <Button  
        android:id="@+id/submitButton"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:text="@string/submit_button"  <!-- Button text (from strings.xml) -->  
        app:layout_constraintEnd_toEndOf="parent"  
        app:layout_constraintStart_toStartOf="parent"  
        app:layout_constraintTop_toBottomOf="@id/nameEditText"  
        app:layout_constraintMarginTop="16dp"/>  

    <!-- TextView: Displays the greeting -->  
    <TextView  
        android:id="@+id/greetingTextView"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:textSize="24sp"  <!-- Font size (scaled pixels for accessibility) -->  
        app:layout_constraintEnd_toEndOf="parent"  
        app:layout_constraintStart_toStartOf="parent"  
        app:layout_constraintTop_toBottomOf="@id/submitButton"  
        app:layout_constraintMarginTop="24dp"/>  

</androidx.constraintlayout.widget.ConstraintLayout>  

Step 2: Define Strings in strings.xml

To avoid hardcoding text (a best practice for localization), store strings in res/values/strings.xml:

<resources>  
    <string name="app_name">FirstKotlinApp</string>  
    <string name="name_hint">Enter your name</string>  <!-- Hint for EditText -->  
    <string name="submit_button">Submit</string>  <!-- Button text -->  
</resources>  

Preview the UI

Click the Design tab in the layout editor to see a preview of your screen. You should see an input field, a button, and an empty text view.

4. Adding Functionality with Kotlin

Now, let’s make the app interactive! We’ll use Kotlin to:

  • Read text from the EditText.
  • Respond to button clicks.
  • Update the TextView with a greeting.

View Binding is a safer alternative to findViewById (which can cause crashes if IDs are misspelled). It generates a binding class for your layout, letting you access UI elements directly.

Enable View Binding in build.gradle

Open app/build.gradle (Module level) and add this to the android block:

android {  
    ...  
    buildFeatures {  
        viewBinding true  
    }  
}  

Click Sync Now to apply the changes.

Step 2: Write Kotlin Code in MainActivity.kt

Open MainActivity.kt (in app/src/main/java/[package]/). Replace the default code with:

package com.yourname.firstkotlinapp  // Replace with your package name  

import androidx.appcompat.app.AppCompatActivity  
import android.os.Bundle  
import com.yourname.firstkotlinapp.databinding.ActivityMainBinding  // Auto-generated binding class  

class MainActivity : AppCompatActivity() {  
    // Declare a binding variable (lateinit = initialize later)  
    private lateinit var binding: ActivityMainBinding  

    override fun onCreate(savedInstanceState: Bundle?) {  
        super.onCreate(savedInstanceState)  

        // Inflate the layout using view binding  
        binding = ActivityMainBinding.inflate(layoutInflater)  
        // Set the content view to the root of the binding layout  
        setContentView(binding.root)  

        // Add a click listener to the submit button  
        binding.submitButton.setOnClickListener {  
            // Get text from the EditText (trim whitespace)  
            val userName = binding.nameEditText.text.toString().trim()  

            // Update the TextView with a greeting  
            if (userName.isNotEmpty()) {  
                binding.greetingTextView.text = "Hello, $userName!"  
            } else {  
                binding.greetingTextView.text = "Please enter your name!"  
            }  
        }  
    }  
}  

Code Explanation:

  • lateinit var binding: Delays initialization of the binding object until onCreate.
  • ActivityMainBinding.inflate(layoutInflater): Generates the binding class for activity_main.xml.
  • setContentView(binding.root): Sets the app’s UI to the root of the layout.
  • setOnClickListener: Listens for button clicks. When clicked:
    • binding.nameEditText.text.toString() reads text from the input field.
    • binding.greetingTextView.text updates the text view with a greeting (or a prompt if the input is empty).

5. Testing the App

Now it’s time to run your app and see it in action!

Step 1: Run on Emulator or Device

  1. Select your emulator/device from the dropdown in the toolbar (e.g., “Pixel 7 API 34”).
  2. Click the Run button (green play icon) or press Shift + F10.

Step 2: Interact with the App

  • The app will launch on your emulator/device.
  • Enter your name in the input field and click Submit.
  • You should see “Hello, [Your Name]!” displayed below the button.

Debugging Tips

  • Logcat: View system messages and errors by going to View > Tool Windows > Logcat. Use Log.d("TAG", "Message") in Kotlin to print debug info:
    import android.util.Log  
    Log.d("MainActivity", "User entered: $userName")  
  • Breakpoints: Click the gutter next to a line of code to set a breakpoint. Run the app in debug mode (bug icon) to pause execution and inspect variables.

6. Enhancing the App (Optional)

Want to take your app further? Try these simple additions:

Add a Second Screen

Use an Intent to navigate to a new activity. For example:

  1. Create a SecondActivity and layout (activity_second.xml).
  2. In MainActivity, modify the button click listener to launch SecondActivity:
    val intent = Intent(this, SecondActivity::class.java)  
    intent.putExtra("USER_NAME", userName)  // Pass data to SecondActivity  
    startActivity(intent)  
  3. In SecondActivity, retrieve the data:
    val userName = intent.getStringExtra("USER_NAME")  
    binding.secondGreetingTextView.text = "Welcome, $userName!"  

Add a Toast Message

Show a temporary pop-up message with Toast:

Toast.makeText(this, "Greeting updated!", Toast.LENGTH_SHORT).show()  

7. Publishing to Google Play (Overview)

Once your app is ready, you can share it with the world via Google Play. Here’s a high-level overview:

Step 1: Prepare Your App

  • Generate a signed APK/App Bundle (Android’s preferred format for distribution). Go to Build > Generate Signed Bundle/APK.
  • Follow the prompts to create a keystore (a file that signs your app to prove it’s authentic).

Step 2: Set Up Google Play Console

  • Sign up for a Google Play Console account ($25 one-time fee).
  • Create a new app listing with details like title, description, screenshots, and pricing.

Step 3: Upload and Publish

  • Upload your signed App Bundle to the Play Console.
  • Fill in content ratings, privacy policies, and distribution details.
  • Click Publish to make your app available on Google Play (may take a few hours to review).

8. Conclusion

Congratulations! You’ve built your first Android app with Kotlin. You learned how to:

  • Set up Android Studio and test on emulators/ devices.
  • Design a UI with XML and ConstraintLayout.
  • Add interactivity with Kotlin and View Binding.
  • Debug and enhance your app.

This is just the beginning—Android development offers endless possibilities (e.g., integrating APIs, using databases, building games). Keep experimenting, and check the references below to learn more!

9. References

Happy coding! 🚀