Sebastian Sebastian - 1 month ago 12
Java Question

Changing menu buttons to normal buttons

case R.id.Delete_Contact:

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.deleteContact)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mydb.deleteContact(id_To_Update);
Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
AlertDialog d = builder.create();
d.setTitle("Are you sure");
d.show();

return true;
default:
return super.onOptionsItemSelected(item);


How can i use this in an button click event ? This works when clicking menu button

Tom Tom
Answer

Use this code...

//intialize button

 button.setOnClickListener(new View.OnClickListener() {


                @Override
                public void onClick(View v) {

                    if (v == button) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(DisplayContact.this);
                        builder.setMessage("Delete")
                                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        mydb.deleteContact(id_To_Update);
                                        Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show();
                                        Intent intent = new Intent(getApplicationContext(),MainActivity.class);
                                        startActivity(intent);
                                    }
                                })
                                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {

                                    }
                                });
                        AlertDialog d = builder.create();
                        d.setTitle("Are you sure");
                        d.show();



                    }
                }
            });