/Android_Kotlin_lesson1_MyFirstApp

How to create my First Mobile App with Kotlin and Android Studio

My First Mobile Application with Android Studio and Kotlin

For further information see this youtube video:

https://www.youtube.com/watch?v=F3fWtxanBLg

https://www.youtube.com/watch?v=vFNpJldBP6A

1. How to create a New Project in Android Studio

Run Android Studio and press the New Project button

image

We select the template option Empty View Activity and press the Next button

image

We input the new project data: activity name, package name, save location, language, minimum SDK and build configuration language

We press the Finish button

image

Then Gradle will configure automatically the project

Note: Please accept to add the Project paths to Microsoft Defender

This is the project folder and files structure

image

2. Design the application User Interface UI

We have to open the file /res/layout/activity_main.xml

image

This is the the UI code

activity_main.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:id="@+id/main"
    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_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

We drag and drop a button into the ConstraintLayout with id main

image

We fix the errors:

We have to set the buttons constraints

Also we have to extract the button name to resources

image

We create a string in resources (/res/values/strings.xml) with the button name

/res/values/strings.xml

<resources>
    <string name="app_name">MyFirstApplication</string>
    <string name="button_first">Button</string>
</resources>

image

We verify also the file /res/layout/activity_main.xml

image

We also have to set the button constraints

image

This is the modified UI code

activity_main.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:id="@+id/main"
    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_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button_first"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_first"
        android:layout_marginTop="16dp"
        app:layout_constraintTop_toBottomOf="@id/textView"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

3. Define the button OnClickListener

This is the original code

MainActivity.kt

package com.example.myfirstapplication

import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
    }
}

This is the modified code

MainActivity.kt

package com.example.myfirstapplication

import android.os.Bundle
import android.widget.Button
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

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

        // Set up window insets
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        // Find the button by its ID
        val button = findViewById<Button>(R.id.button_first)

        // Set an OnClickListener on the button
        button.setOnClickListener {
            // Create and show a dialog
            val dialog = AlertDialog.Builder(this)
                .setTitle("Dialog Title")
                .setMessage("This is a simple dialog message.")
                .setPositiveButton("OK") { dialog, _ ->
                    dialog.dismiss()
                }
                .create()
            dialog.show()
        }
    }
}

4. How to run the application

As a mandatory prerequesite we have to create AVD Android Virtual Device before running the application

See this post:

Now we can press the Running Devices button and then the Run 'app'

image

image

image

5. Code explained

This code is an Android application written in Kotlin

It defines the MainActivity class, which extends AppCompatActivity and represents the main activity of the application

Here's a brief explanation of the key parts:

Package Declaration:

package com.example.myfirstapplication

This specifies the package name for the class

Imports:

import android.os.Bundle
import android.widget.Button
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

These import necessary classes from the Android SDK and AndroidX libraries for the functionality used in the activity

MainActivity Class Declaration:

class MainActivity : AppCompatActivity() {

This declares the MainActivity class, inheriting from AppCompatActivity

onCreate Method:

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

The onCreate method is the entry point for the activity

It is called when the activity is first created

It performs the following actions:

Calls the super.onCreate method to ensure proper initialization

Enables edge-to-edge display using enableEdgeToEdge()

Sets the content view to activity_main.xml using setContentView

Setting Window Insets:

ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
    val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
    v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
    insets
}

This block sets a listener to apply window insets to the main view (with ID main)

It adjusts the padding of the view to accommodate system bars (like status and navigation bars)

Button Setup:

val button = findViewById<Button>(R.id.button_first)

This line finds a button in the layout with the ID button_first

Button OnClickListener:

button.setOnClickListener {
    val dialog = AlertDialog.Builder(this)
        .setTitle("Dialog Title")
        .setMessage("This is a simple dialog message.")
        .setPositiveButton("OK") { dialog, _ ->
            dialog.dismiss()
        }
        .create()
    dialog.show()
}

This block sets an OnClickListener on the button

When the button is clicked:

It creates an AlertDialog with a title, message, and an "OK" button

The "OK" button dismisses the dialog when clicked

The dialog is then shown on the screen

In summary, this code sets up an Android activity with a button that, when clicked, displays a dialog with a message

The activity also handles window insets to ensure proper layout adjustments for system bars