For those who are interrested in a way to implement a dialog box to get a result, but without using onActivityResult here is an example using callbacks. This way you can call this custom dialog box from anywhere and do something according to the choice.
A SHORT WAY
public void getDialog(Context context, String title, String body,
DialogInterface.OnClickListener listener){
AlertDialog.Builder ab = new AlertDialog.Builder(context);
ab
.setTitle(title)
.setMessage(body)
.setPositiveButton("Yes", listener)
.setNegativeButton("Cancel", listener)
;//.show();
Dialog d=ab.create();
d.setCanceledOnTouchOutside(false);
d.show();
}
private void showDialog(){
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
//DO
break;
case DialogInterface.BUTTON_NEGATIVE:
//DO
break;
}
}
};
getDialog(
this,
"Delete",
"Are you sure to delete the file?",
dialogClickListener
);
}
Another way, suitable if you have to implement different variations of dialog boxes since you can define the all the actions in a single place.
MyDialog.java
public class MyDialog{
public void deleteDialog(Context context){
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
if(listener!=null)
listener.onDeleteDialogResponse(true);
break;
case DialogInterface.BUTTON_NEGATIVE:
if(listener!=null)
listener.onDeleteDialogResponse(false);
break;
}
}
};
AlertDialog.Builder ab = new AlertDialog.Builder(context);
ab.setMessage("Are you sure to delete?")
.setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("Cancel", dialogClickListener)
.show();
}
/** my listner */
public interface MyDialogListener{
public void onDeleteDialogResponse(boolean respononse);
}
private MyDialogListener listener;
public void setListener(MyDialogListener listener) {
this.listener = listener;
}
}
Use it like this
private void showDialog(){
MyDialog dialog=new MyDialog();
dialog.setListener(new MyDialog.MyDialogListener() {
@Override
public void onDeleteDialogResponse(boolean respononse) {
if(respononse){
//toastMe("yessss");
//DO SOMETHING IF YES
}else{
//toastMe("noooh");
//DO SOMETHING IF NO
}
}
});
dialog.deleteDialog(this);
}