java - 警报对话框的处理结果如何? (安卓)

标签 java android android-alertdialog

我正在开发一个可以生成警报对话框的小类。该类的构造函数如下所示:

void popupMessage(String title, String message, String pText, String nText, boolean cancelable) {
        setPopupResult(999);
        AlertDialog.Builder dialog = new AlertDialog.Builder(currentActivity);
        dialog.setMessage(message).setCancelable(cancelable);
        dialog.setNegativeButton(nText, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                setPopupResult(0);
            }
        });
        dialog.setPositiveButton(pText, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                setPopupResult(1);
            }
        });

        AlertDialog alert = dialog.create();
        alert.setTitle(title);
        alert.show();
    }

正如您所见,根据按下"is"或“否”按钮,代码将私有(private)变量的值设置为 0 或 1,可以通过 getter 方法访问该值。 (顶部的值设置为999,这表明用户还没有按下任何按钮)

我面临的问题是,在调用 Activity 中,我应该能够捕获 popupResult 变量从 999 更改为 0 或 1 的时间。我该怎么做?

(我可能会错误地处理这样的警报对话框,请随时教育我)

最佳答案

由于用户单击对话框按钮与显示对话框时是异步的,因此一种方法是为您的方法提供某种回调,该回调在单击按钮时调用。

示例:

/* define this inside your dialog class */
public interface Callback {
    void onOkClicked();
    void onCancelClicked();
}

void popupMessage(String title, String message, String pText, String nText, boolean cancelable, Callback callback) {
    ...
        /* positive button clicklistener, for negative button, use callback.onCancelClicked() */
        public void onClick(DialogInterface dialog, int which) {
            callback.onOKClicked();
        }
    ... 
}

/* Using the method */
popupMessage(..., new Callback() {
    void onOKClicked() {
        /* do something when OK was clicked */
    }

    void onCancelClicked() {
        /* do something when Cancel was clicked */
    }
});   

关于java - 警报对话框的处理结果如何? (安卓),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53682658/

相关文章:

android - BOOT_COMPLETED 后警报对话框中的空指针异常

android - AlertDialog MultipleChoice 不显示项目

java - JMonkeyEngine 旋转和四元数有什么区别?

android - 错误:不是语句(查询)

java - 如何在不在 android 中的 Activity 上添加 map fragment 的情况下获取我的位置?

android - 如何将 ArrayAdapter 发送到 ListActivity

Android:警报对话框和 fragment

java - 在 Android 中返回 SQLite 表的所有列

java - Android/Java 中的 "passive data structure"是什么?

java - 为什么不通过在 sar/META.INF/jboss-service.xml 中工作的 SystemPropertiesService 配置 JBoss 系统属性