Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/207.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
监听器中的java android返回方法?_Java_Android - Fatal编程技术网

监听器中的java android返回方法?

监听器中的java android返回方法?,java,android,Java,Android,我是Java Android新手,我面临这个问题,我不知道它叫什么,下面是我的代码: public boolean msgBox(String title, String text) { boolean bReturn = false; AlertDialog.Builder adb = new AlertDialog.Builder(this); adb.setCancelable(false); adb.setTitle(title); adb.se

我是Java Android新手,我面临这个问题,我不知道它叫什么,下面是我的代码:

public boolean msgBox(String title, String text) {
    boolean bReturn = false;
    AlertDialog.Builder adb = new AlertDialog.Builder(this);

    adb.setCancelable(false);
    adb.setTitle(title);
    adb.setMessage(text);
    adb.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            //this suppose tell msgBox return true
        }
    });

    adb.setNegativeButton("Yes", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            //this suppose tell msgBox return false
        }
    });

    adb.show();

    return bReturn;
}

现在,当用户单击正/负按钮时,我如何告诉msgBox返回真/假?谢谢,这是不可能的,因为该方法将在对话框打开后结束。该对话框将在方法完成后继续打开

为了将信息返回给msgBox调用者,您需要提供一个回调函数

您可以创建一个接口,将其传递到msgBox,然后在对话框按钮中调用它

public interface OnDialogButtonClickedCallback {
    public void onDialogButtonClicked(boolean wasPositive);
}
像这样传递它:

public boolean msgBox(String title, String text, final OnDialogButtonClickedCallback callback)
@Override
public void onClick(DialogInterface dialog, int which) {
    if(callback != null) {
        callback.onDialogButtonClicked(true);
    }
}
在按钮中使用它,如下所示:

public boolean msgBox(String title, String text, final OnDialogButtonClickedCallback callback)
@Override
public void onClick(DialogInterface dialog, int which) {
    if(callback != null) {
        callback.onDialogButtonClicked(true);
    }
}
在上面的函数中,您确定变量int单击了哪个按钮,而int是哪个(例如:Yes是第一个,No是第二个)

bReturn应该是全球性的


因为每个按钮都有单独的侦听器,所以您甚至不必区分它们,因为它们是单独的侦听器。

如果单击一个值,设置一个布尔变量,然后只返回该变量。@Zizouz212这样,方法将在单击任何内容之前返回。