Full tutorial is given below. Dear Viewer we are working hard to maintain this website. We doesn't want any think from you. Its just a humble request If you thinks that this posts helps you please share this post with your friends.
How to create a SingleChoice AlertDialog in Android
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"> <Button android:id="@+id/showsnackbarbtn" android:text="Show Alert Dialog" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/txtView" android:text="Selected Item" android:textSize="20sp" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>
MainActivity.java
package com.usmtip.myapplication; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { String[] listItems; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final TextView textView = findViewById(R.id.txtView); Button showDialog = findViewById(R.id.showsnackbarbtn); showDialog.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { listItems = new String[]{"Item 1", "Item 2", "Item 3"}; AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this); mBuilder.setTitle("Choose an item"); mBuilder.setSingleChoiceItems(listItems, -1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { textView.setText(listItems[i]); dialogInterface.dismiss(); } }); // Set the neutral/cancel button click listener mBuilder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Do something when click the neutral button dialog.cancel(); } }); AlertDialog mDialog = mBuilder.create(); mDialog.show(); } }); } }
0 Comments: