一個自定義dialog提供確定和取消按鈕的回撥介面
阿新 • • 發佈:2019-01-06
public class MessageDialog { Context context; AlertDialog dialog; AlertDialog.Builder builder; private MessageDialog() {} private static MessageDialog messageDialog = new MessageDialog(); public static MessageDialog getInstance() {return messageDialog;} OnCancelClickListener cancelClickListener; OnCommitClickListener commitClickListener; public void showMessageDialog() { if (dialog != null && !dialog.isShowing()) { dialog.show(); } } public void cancelMessageDialog() { if(dialog != null && dialog.isShowing()) { dialog.cancel(); } } public AlertDialog generateDialog() { if (builder == null) { return null; } dialog = builder.create(); return dialog; } public void initDialog(Context context, String message) { this.initDialog(context, "是", "否", message); } /** * 初始化對話方塊 * @param context * @param message */ public void initDialog(Context context, String btnCommit, String btnCancel, String message) { this.context = context; builder = new AlertDialog.Builder(context).setMessage(message).setPositiveButton(btnCommit, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if(commitClickListener == null) { return; } commitClickListener.onCommit(); } }).setNegativeButton(btnCancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if(cancelClickListener == null) { return; } cancelClickListener.onCancel(); } }); } public OnCancelClickListener getCancelClickListener() { return cancelClickListener; } public MessageDialog setCancelClickListener(OnCancelClickListener cancelClickListener) { this.cancelClickListener = cancelClickListener; return this; } public OnCommitClickListener getCommitClickListener() { return commitClickListener; } public MessageDialog setCommitClickListener(OnCommitClickListener commitClickListener) { this.commitClickListener = commitClickListener; return this; } public void setAlertMessage(String message) { builder.setMessage(message); } public interface OnCancelClickListener { public void onCancel(); } public interface OnCommitClickListener { public void onCommit(); } }
在別的類中使用的例子
MessageDialog messageDialog = MessageDialog.getInstance(); messageDialog.initDialog(context, "是", "否", "報備成功,是否繼續?"); messageDialog.generateDialog(); messageDialog.showMessageDialog(); messageDialog.setCommitClickListener(new MessageDialog.OnCommitClickListener() { @Override public void onCommit() { fragment.viewReset(); } }); messageDialog.setCancelClickListener(new MessageDialog.OnCancelClickListener() { @Override public void onCancel() { fragment.getActivity().onBackPressed(); } });