Wednesday 31 October 2012

Android Dialogs Tutorial for Beginner(radio dialog, checkbox dialog,list dialog,progress dialog, custom dialog)

activity_main.xml



<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/linear"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#2662df"
    android:orientation="vertical" >

    <Button
        android:id="@+id/radio_dialog"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="10dp"
        android:text="SingleChoice" />

    <Button
        android:id="@+id/list_dialog"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="List" />

    <Button
        android:id="@+id/checkbox_dialog"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="MultiChoice" />

    <Button
        android:id="@+id/progress_dialog"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Progress" />

    <Button
        android:id="@+id/custom_dialog"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Custom" />

    <Spinner
        android:id="@+id/spinner_dialog"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:entries="@array/labelpos"
        android:prompt="@string/hello_world"
        android:text="Spinner" />

</LinearLayout>

listitem.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" android:layout_gravity="center_vertical"/>

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello Android"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="10dp"/>

</LinearLayout>



MainActivity.java

package com.example.dialoglist;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Color;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.NavUtils;

public class MainActivity extends Activity {
    final Context context = this;
    Button radio, listdialog, checkbox, progress, custom;
    ListView lv;
    String[] listitem = { "one", "two", "three", "four", "five", "six",
            "seven", "eight", "nine", "ten" };
    LinearLayout ll;
    Spinner mSpinner;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        radio = (Button) findViewById(R.id.radio_dialog);
        listdialog = (Button) findViewById(R.id.list_dialog);
        checkbox = (Button) findViewById(R.id.checkbox_dialog);
        progress = (Button) findViewById(R.id.progress_dialog);
        custom = (Button) findViewById(R.id.custom_dialog);
        ll = (LinearLayout) findViewById(R.id.linear);
        ll.setBackgroundColor(Color.GRAY);
        mSpinner=(Spinner)findViewById(R.id.spinner_dialog);
      

        custom.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
              
                ll.setBackgroundColor(Color.CYAN);
                Dialog mDialog = new Dialog(context);
                mDialog.setContentView(R.layout.listitem);
                mDialog.setTitle("Custom Dialog...");
                mDialog.show();
                mDialog.setOnCancelListener(new OnCancelListener() {

                    @Override
                    public void onCancel(DialogInterface dialog) {
              
                        ll.setBackgroundColor(Color.GRAY);

                    }
                });
            }
        });

        progress.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                ll.setBackgroundColor(Color.GREEN);
              
                ProgressDialog progresdialog = new ProgressDialog(context);
                progresdialog.setMessage("Loading,Please wait...");
                progresdialog.setButton("Cancel",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
      
                                dialog.dismiss();
                                ll.setBackgroundColor(Color.GRAY);
                            }
                        });
                progresdialog.show();
            }
        });
      
        checkbox.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
      
                ll.setBackgroundColor(Color.MAGENTA);
                final CharSequence[] items = { "Gujrat", "Rajasthan",
                        "Maharastra", "Panjab", "Madhya Pradesh", "Hariyana",
                        "Bihar" };
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle("Select State");

                builder.setMultiChoiceItems(items, null,
                        new DialogInterface.OnMultiChoiceClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which, boolean isChecked) {
                                // TODO Auto-generated method stub
                                if (isChecked)
                                    Toast.makeText(getApplicationContext(),
                                            items[which], Toast.LENGTH_SHORT)
                                            .show();
                                ll.setBackgroundColor(Color.GRAY);
                            }
                        });
                AlertDialog alert = builder.create();
                alert.show();
            }
        });
        listdialog.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                ll.setBackgroundColor(Color.YELLOW);
                final CharSequence[] items = { "Mango", "Banana", "Apple" };
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle("Select Fruit");
                builder.setItems(items, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        dialog.cancel();
                        ll.setBackgroundColor(Color.GRAY);
                    }
                });
                AlertDialog alert = builder.create();
                alert.show();
            }
        });

        radio.setOnClickListener(new OnClickListener() {

            // add button listener

            @Override
            public void onClick(View arg0) {
                ll.setBackgroundColor(Color.RED);
                final CharSequence[] items = { "Red", "Green", "Blue" };

                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle("Pick a color");
                builder.setSingleChoiceItems(items, -1,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int item) {
                                Toast.makeText(getApplicationContext(),
                                        items[item], Toast.LENGTH_SHORT).show();
                                dialog.cancel();
                                ll.setBackgroundColor(Color.GRAY);
                            }
                        });
                AlertDialog alert = builder.create();
                alert.show();
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}


MainScreen




Radio_Dialog




List_dialog
Checkbox_Dialog

Progress_Dialog

Custom_Dialog
You can download full source from here

8 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. hello , your tutorial is good but i have a question : how can i save the state of the checkbox dialog ? i mean let's say i want to re-open it i'd like to see the one who are checked is it possible ?

    ReplyDelete
    Replies
    1. Hi Niiaou
      yes, it's possible.
      Here I am passing null in this code(it means no checked item)
      builder.setMultiChoiceItems(items, null,
      new DialogInterface.OnMultiChoiceClickListener()

      Just replace above line with
      final boolean[]check={true,false,true,false,true,false,true,false};
      AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
      builder.setTitle("Select State");

      builder.setMultiChoiceItems(items, check,
      new DialogInterface.OnMultiChoiceClickListener()


      If you want to recover checked items when you re-open then you have to update elements in check array and store it somewhere as per you requirement. And pass it when you re-open.
      for more details have look at http://developer.android.com/reference/android/app/AlertDialog.Builder.html#setMultiChoiceItems%28java.lang.CharSequence[],%20boolean[],%20android.content.DialogInterface.OnMultiChoiceClickListener%29

      -Ketan

      Delete
  3. This comment has been removed by the author.

    ReplyDelete
  4. 07-15 09:20:05.098: E/AndroidRuntime(1725): java.lang.IndexOutOfBoundsException: Invalid index 3, size is 0

    i am getting this error while use long press delete is there any solution please help me out

    ReplyDelete
  5. Great post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.
    Click here:
    angularjs training in chennai
    Click here:
    angularjs training in velarchery

    ReplyDelete