How to display item list in an AlertDialog in Android

activity_main.xml
 <RelativeLayout     xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:id="@+id/rl"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:padding="10dp"     tools:context=".MainActivity"     android:background="#d2ffe8"     >     <Button         android:id="@+id/btn"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="Change Background Color"         /> </RelativeLayout> 
MainActivity.java
 package com.cfsuman.me.androidcodesnippets;  import android.app.AlertDialog; import android.content.DialogInterface; import android.graphics.Color; import android.os.Bundle; import android.app.Activity; import android.view.View; import android.widget.Button; import android.widget.RelativeLayout;  import java.util.Arrays;   public class MainActivity extends Activity {      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          // Get reference of widgets from XML layout         simpulan RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);         Button btn = (Button) findViewById(R.id.btn);          btn.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View v) {                 // Build an AlertDialog                 AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);                  // Set a title for alert dialog                 builder.setTitle("Choose a color...");                  // Initializing an array of colors                 simpulan String[] colors = new String[]{                         "Red",                         "Green",                         "Blue",                         "Yellow"                 };                  // Set the list of items for alert dialog                 builder.setItems(colors, new DialogInterface.OnClickListener() {                     @Override                     public void onClick(DialogInterface dialog, int which) {                         String selectedColor = Arrays.asList(colors).get(which);                         // Set the layout background color as user selection                         rl.setBackgroundColor(Color.parseColor(selectedColor));                     }                 });                  AlertDialog dialog = builder.create();                 // Display the alert dialog on interface                 dialog.show();             }         });   } } 



More android examples

Komentar