Tuesday, February 15, 2011

How to create Yes, No Alert boxes


If you want to confirmation alert, you can use setPositiveButton() and setNagativeButton().

ex-

package com.yesno;

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

public class yesnoalert extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AlertDialog.Builder alert_box=new AlertDialog.Builder(this);
alert_box.setIcon(R.drawable.icon);
alert_box.setMessage("This is Yes no alert box");
alert_box.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Yes Button Clicked",Toast.LENGTH_LONG).show();
}
});
alert_box.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "No Button Clicked", Toast.LENGTH_LONG).show();
}
});
alert_box.show();
setContentView(R.layout.main);
}
}

If You want to add Title to that alert box add below line

alert_box.setTitle("Confirm Alert");


Sameera Nadirani Handapangoda

1 comment: