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.
MainActivity.java
Step 1: Create a new project OR Open your project
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/showsnackbarbtn"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.java
package com.blogspot.devofandroid.myapplication;import android.content.DialogInterface;import android.os.Bundle;import android.support.v7.app.AlertDialog;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;import android.widget.TextView;import android.widget.Toast;import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class MainActivity extends AppCompatActivity {String[] listItems;@Overrideprotected void onCreate(final 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() {@Overridepublic 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() {@Overridepublic void onClick(DialogInterface dialogInterface , int i) {textView.setText(listItems[i]);dialogInterface.dismiss();}});// Set the neutral/cancel button click listenermBuilder.setNeutralButton("Cancel" , new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog , int which) {// Do something when click the neutral buttondialog.cancel();}});AlertDialog mDialog = mBuilder.create();mDialog.show();}});}}
0 Response to "How To Create A Singlechoice Alertdialog In Android"