CarbonAssassin CarbonAssassin - 5 months ago 20
Android Question

How do i add a close button to this alert dialog in Android

I need help implementing the code to add a negative or positive button to close my alert dialogue (any help would be much appreciated). I think some of my punctuation in the code needs altering as well so any help would be great :)

package kevin.erica.box;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.Random;

public class TheKevinAndEricaBoxActivity extends Activity {
/** Called when the activity is first created. */
private String[] myString;
private String list;
private String[] myString2;
private String list2;
private static final Random rgenerator = new Random();
private static final Random rgenerator2 = new Random();

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Resources res = getResources();

myString = res.getStringArray(R.array.myArray);

list = myString[rgenerator.nextInt(myString.length)];

myString2 = res.getStringArray(R.array.myArray2);

list2 = myString2[rgenerator.nextInt(myString2.length)];

ImageButton ib = (ImageButton) findViewById(R.id.imagebutton1);
ib.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View erica) {
AlertDialog.Builder b = new AlertDialog.Builder(
TheKevinAndEricaBoxActivity.this);
b.setMessage(myString[rgenerator.nextInt(myString.length)]);
b.setTitle(R.string.title1);
Dialog d = b.create();
d.show();

}
});
}
}

Answer

You can use the below code in your app::::

AlertDialog.Builder b = new AlertDialog.Builder(TheKevinAndEricaBoxActivity.this);
b.setMessage(myString[rgenerator.nextInt(myString.length)]);
b.setTitle(R.string.title1); 
b.setPositiveButton("Button Text", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which){
    //stuff you want the button to do
}
});
b.setNegativeButton("Button Text", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which){
    //stuff you want the button to do
}
});