Sunday 21 April 2013

Alert Dialog : Dialog with Item List Example in Android

activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <Button
        android:id="@+id/done_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="DONE" />

</RelativeLayout>

MainActivity.java

package com.example.alertdialogex;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {

    private Button mDoneButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mDoneButton = (Button) findViewById(R.id.done_button);
        mDoneButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        final CharSequence[] items = {
                "Rajesh", "Mahesh", "Vijayakumar"
        };

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Make your selection");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                // Do something with the selection
                mDoneButton.setText(items[item]);
            }
        });
        AlertDialog alert = builder.create();
        alert.show();

    }
}

 Output :






















7 comments:

  1. Thank you so very much for this, this was very fast and precise for me.

    ReplyDelete
  2. Thanks for this tutorial.How to make custom dialog box with list view?

    ReplyDelete
  3. Nothing more clear than this example: simple and functional.
    Thanks (y)

    ReplyDelete
  4. Thanks, way better than the explanation on the android website!

    ReplyDelete
  5. Brief, to the point and clear! Thanks.

    ReplyDelete