对于那些想要实现一个对话框以获取结果,但不想使用onActivityResult的人,这里提供了一个使用回调函数的示例。这样,您可以从任何地方调用此自定义对话框,并根据选择执行某些操作。
简短方式
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)
;
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:
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
getDialog(
this,
"Delete",
"Are you sure to delete the file?",
dialogClickListener
);
}
另一种方式,适用于您需要实现不同变体的对话框,因为您可以在一个地方定义所有操作。
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();
}
public interface MyDialogListener{
public void onDeleteDialogResponse(boolean respononse);
}
private MyDialogListener listener;
public void setListener(MyDialogListener listener) {
this.listener = listener;
}
}
像这样使用
private void showDialog(){
MyDialog dialog=new MyDialog();
dialog.setListener(new MyDialog.MyDialogListener() {
@Override
public void onDeleteDialogResponse(boolean respononse) {
if(respononse){
}else{
}
}
});
dialog.deleteDialog(this);
}