Sunday 28 July 2013

Dailog With Items Demo


Demo:



1)MainActivity.java:
package com.venky.dialogwithitems;

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

public class MainActivity extends Activity {

      String[] items = { "Red", "Green", "Black", "White", "Yellow", "Orange" };

      Context ctx;

      @Override
      protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            ctx = this;

            Button btn = (Button) findViewById(R.id.btn1);
            btn.setOnClickListener(new OnClickListener() {

                  @Override
                  public void onClick(View v) {
                        AlertDialog.Builder alert = new AlertDialog.Builder(ctx);
                        alert.setTitle("Colors");
                        alert.setItems(items, new DialogInterface.OnClickListener() {

                              @Override
                              public void onClick(DialogInterface dialog, int pos) {
                                    Toast.makeText(ctx, "U Clicked => " + items[pos], 3000)
                                                .show();
                              }
                        });
                        alert.show();
                  }
            });
      }
}

2)main.xml: 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/RelativeLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#5F04B4"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btn1"
        android:layout_width="200dp"
        android:layout_height="40dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Click Me"
        android:background="#ffffff"
        android:textColor="#000000"
        android:textSize="20dp"
        android:textStyle="bold" />

</RelativeLayout>
 
3)Download this Project Click Here

No comments:

Post a Comment