Monday, December 31, 2012

Create Dialog with options, using AlertDialog.Builder

Hi Guys!

In this tutorial I am sharing the code about the Alert Dialog with select option in android.
More details about the Alert Dialog visit the android developer site Alert Dialog

Lets start the coding part.

activty_main.xml






MainActivity.java

package com.sunil.alertdialogwithoption;

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

public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button buttonStartDialog = (Button)findViewById(R.id.button_alert);
buttonStartDialog.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
StartDialog();
}});
}

private void StartDialog(){
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);
myAlertDialog.setTitle("My Alert Dialog");
myAlertDialog.setMessage("It provide options for user to select");
myAlertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(getApplicationContext(), "'Yes' button clicked", Toast.LENGTH_LONG).show();
}
});
myAlertDialog.setNeutralButton("Option 1", new DialogInterface.OnClickListener() {

// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(getApplicationContext(), "'Option 1' button clicked", Toast.LENGTH_LONG).show();
}
});
myAlertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {

// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(getApplicationContext(), "'No' button clicked", Toast.LENGTH_LONG).show();
}
});
myAlertDialog.show();
}

}

 You can download the source code Alert Dialog.

Cheers Guys! 

Rocky

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation.

0 comments:

Post a Comment

 

Copyright @ 2013 Android Developers Tipss.