- MultiChoice AlertDialog contains list of item with Text and Checkbox .
- To specify the items for the list, call setMultiChoiceItems by passing an array of String for text to display and array of boolean values to display checked and unchecked status for respective items.
XML Layout
Create XML Layout activity_main.xml , this will be set as content view for launcher Activity (MainActivity.kt) .
file : activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="30dp" tools:context=".MainActivity"> <androidx.appcompat.widget.AppCompatButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="show MultiChoice Dialog" android:textSize="20sp" android:textAllCaps="false" android:onClick="multiChoiceDialog"/> </LinearLayout>
Activity
- Create a koltin class MainActivity.kt and extend it to AppCompatActivity class .
- Override onCreate function and set the content of this MainActivity with above defined xml layout (activity_main.xml).
package com.tutorialsbuzz.multichoicealertdialog import android.content.DialogInterface import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.View import android.widget.Toast import androidx.appcompat.app.AlertDialog class MainActivity : AppCompatActivity() { val multiChoiceList = linkedMapOf<String, Boolean>( "English" to false, "Hindi" to false, "French" to false, "Spanish" to false, "Portuguese" to false, "German" to false, "Italian" to false, "Korean" to false, "Japanese" to false, "Chinese" to false ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } fun multiChoiceDialog(view: View) { val builder = AlertDialog.Builder(this) builder.setTitle("Select Languages") builder.setMultiChoiceItems(multiChoiceList.keys.toTypedArray(), multiChoiceList.values.toBooleanArray(), { dialogInterface, which, isChecked -> multiChoiceList.set(multiChoiceList.keys.toTypedArray().get(which), isChecked) val status = if (isChecked) { " :is checked" } else { " :is un-checked" } Toast.makeText( this@MainActivity, "item: " + multiChoiceList.keys.toTypedArray().get(which) + status, Toast.LENGTH_SHORT ).show() }) builder.setPositiveButton("ok", DialogInterface.OnClickListener { dialog, id -> Log.d("Selected Items", multiChoiceList.toString()) dialog.dismiss() }) builder.setNegativeButton("cancel", { dialog, id -> dialog.dismiss() }) val alertDialog = builder.create() alertDialog.show() } }
No comments:
Post a Comment