Adv

Kotlin Android – AlertDialog with List

 

This is a Kotlin android tutorial. We will see how to create an alert dialog that has a List of data.

The user clicks a List item and we show it in a Toast message.

What is Kotlin?

Kotlin is a programming language targeting the Java
platform. Kotlin is concise, safe, pragmatic, and focused on interoperability with Java code.

Kotlin is usble almost everywhere Java is used today – for server-side development, Android apps, and much more.

Kotlin like Java is a statically typed programming language. This implies the type of every expression in a program is known at compile time, and the compiler can validate
that the methods and fields you’re trying to access exist on the objects you’re using.

Defining Packages in Kotlin

Normally classes are organized in packages in Java. This applies to Kotlin as well.

Package specification should be at the top of the source file:

package info.camposha
import java.util.*
class Starter{
    ...
}

However, be aware that it’s not required to match directories and packages: source files can be placed arbitrarily in the file system.

Defining Functions in Kotlin

Roughly speaking, functions in Kotlin are the equivalent of methods in java.

Functions can take input parameters and can return values. Here’s such a function:

fun sum(a: Int, b: Int): Int {
    return a + b
}

This can be condensed into a single line given that it has an expression body and we can infer the retur types:

fun sum(a: Int, b: Int) = a + b

However, if functions do not return any meaningful value:

fun printSum(a: Int, b: Int): Unit {
    println("sum of $a and $b is ${a + b}")
}

Let’s go.

activity_main.xml

Here’s our layout.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="info.camposha.kotlindialoglist.MainActivity">

    <TextView
        android:id="@+id/headerLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:fontFamily="casual"
        android:text="Android Simple AlertDialog"
        android:textAllCaps="true"
        android:textSize="24sp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/showAlertID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Alert Dialog"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        />

</RelativeLayout>

MainActivity.kt

Here’s our main activity:

package info.camposha.kotlindialoglist

import android.app.Activity
import android.app.AlertDialog
import android.os.Bundle
import android.widget.Button
import android.widget.Toast

class MainActivity : Activity() {

    private lateinit var myDialog: AlertDialog

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

        //REFERENCE BUTTON AND SHOW IT.
        val showBtn = findViewById<Button>(R.id.showAlertID)
        showBtn.setOnClickListener { showAlert() }

    }

    /*
    CREATE AN ALERT DIALOG AND SHOW IT
     */
    private fun showAlert() {
        //INSTANTIATE ALERTDIALOG BUILDER
        val myBuilder = AlertDialog.Builder(this)
        //DATA SOURCE
        val nebulae = arrayOf<CharSequence>("Boomerang", "Orion", "Witch Head", "Ghost Head", "Black Widow", "Flame", "Cone")
        //SET PROPERTIES USING METHOD CHAINING
        myBuilder.setTitle("Science Tips").setItems(nebulae) { dialogInterface, position -> Toast.makeText(this@MainActivity, nebulae[position].toString(), Toast.LENGTH_SHORT).show() }
        //CREATE DIALOG
        myDialog = myBuilder.create()
        //SHOW DIALOG
        myDialog.show()
    }
}
Kotlin Android AlertDialog List

Kotlin Android AlertDialog List

Best regards.

Share
Adv



Share an Example

Share an Example

Browse
What is the capital of Egypt? ( Cairo )