Latest News

How To Create A Singlechoice Alertdialog In Android (Kotlin)

     DESCRIPTION     

In this tutorial we will create alert obrolan with single choice from list of items. We will create a button that show alert obrolan when that button is clicked , a TextView that shows the selected item from dialog.
SingleChoice AlertDialog in Android (Kotlin)

     VIDEO     


     SOURCE CODE     

Step 2: Code

activity_main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout 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"android:padding="20dp"android:orientation="vertical"tools:context=".MainActivity"><Buttonandroid:id="@+id/showAlertDialogBtn"android:text="Show Alert Dialog"android:layout_width="match_parent"android:layout_height="wrap_content" /><TextViewandroid:id="@+id/txtView"android:text="Selected Item"android:textSize="20sp"android:layout_width="match_parent"android:layout_height="wrap_content" /></LinearLayout>

MainActivity.kt
package com.blogspot.atifsoftwares.myapplicationimport android.support.v7.app.AppCompatActivityimport android.os.Bundleimport android.support.v7.app.AlertDialogimport kotlinx.android.synthetic.main.activity_main.*class MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)showAlertDialogBtn.setOnClickListener {val listItems = arrayOf("Item 1" , "Item 2" , "Item 3")val mBuilder = AlertDialog.Builder(this@MainActivity)mBuilder.setTitle("Choose an item")mBuilder.setSingleChoiceItems(listItems , -1) { dialogInterface , i ->txtView.text = listItems[i]dialogInterface.dismiss()}// Set the neutral/cancel button click listenermBuilder.setNeutralButton("Cancel") { obrolan , which ->// Do something when click the neutral buttondialog.cancel()}val mDialog = mBuilder.create()mDialog.show()}}}

Step 3: Output

SingleChoice AlertDialog in Android (Kotlin)
SingleChoice AlertDialog in Android (Kotlin)
SingleChoice AlertDialog in Android (Kotlin)
SingleChoice AlertDialog in Android (Kotlin)
SingleChoice AlertDialog in Android (Kotlin)
SingleChoice AlertDialog in Android (Kotlin)

0 Response to "How To Create A Singlechoice Alertdialog In Android (Kotlin)"