【问题标题】:Getting return value from onClickListener of Android从Android的onClickListener获取返回值
【发布时间】:2013-03-21 10:08:17
【问题描述】:

我可以将变量设置为 web 开发中的会话等上下文吗?

这是我的代码,一旦 Android 应用程序启动,我将在其中开发一个确认框:

package com.example.alertboxandloadingwidgets;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Boolean result = showConfirmationBox("Are you sure you want to do this",
        this);
    }
    public Boolean showConfirmationBox(String messageToShow, final Context context) {
        // prepare the alert box
        AlertDialog.Builder alertbox = new AlertDialog.Builder(context);
        // set the message to display
        alertbox.setMessage(messageToShow);
        // set a positive/yes button and create a listener
        alertbox.setPositiveButton("Yes",
        new DialogInterface.OnClickListener() {
            // do something when the button is clicked
            public void onClick(DialogInterface arg0, int arg1) {
                Toast.makeText(context,
                    "'Yes' button clicked", Toast.LENGTH_SHORT)
                    .show();
            }
        });
        // set a negative/no button and create a listener
        alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
            // do something when the button is clicked
            public void onClick(DialogInterface arg0, int arg1) {
                Toast.makeText(context, "'No' button clicked",
                Toast.LENGTH_SHORT).show();
            }
        });
        // display box
        alertbox.show();
    }
}

但我希望如果单击yes 按钮,则它必须返回true,如果单击no 按钮,则它必须返回false。

但我不能这样做,因为onClickListener 的返回类型是无效的。

更新

但问题是我已将其设为通用意味着此方法我必须在 CommonUtilities 类中编写,其中任何活动都可以使用此方法。所以我必须设置或重置我调用此方法的结果参数的值。

【问题讨论】:

  • 你不能这样做。 Android 对话框是异步的,因此您需要相应地重构代码。
  • 那么我必须允许什么方法意味着我应该在首选项中有一些通用参数。所以我必须设置或重置它的值。
  • 你想错了。在 android 没有办法 做一个同步阻塞警报对话框。你必须重构它。一种方法是使用活动而不是对话框;调用它以获得结果并根据单击的按钮返回不同的结果;然后处理onActivityResult 中的结果。相信我,如果可能的话,Android 会在标准 API 中进行这样的调用。

标签: java android android-widget


【解决方案1】:

Android 对话框是异步的,因此您需要重构代码来处理这个问题。我猜你打算这样做:

boolean result = showConfirmation(...);
if(result) {
    //do something
}
else {
    //do something else
}

您可以通过以下方式获得相同的结果:

public class MainActivity extends Activity {
    private boolean result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        showConfirmationBox("Are you sure you want to do this", this);
    }

    private doOnTrueResult() {
        result = true;
        //do something
    }

    private doOnFalseResult() {
        result = false;
        //do something else
    }

    public void showConfirmationBox(String messageToShow, final Context context) {

        // prepare the alert box
        AlertDialog.Builder alertbox = new AlertDialog.Builder(context);

        // set the message to display
        alertbox.setMessage(messageToShow);

        // set a positive/yes button and create a listener
        alertbox.setPositiveButton("Yes",
        new DialogInterface.OnClickListener() {

            // do something when the button is clicked
            public void onClick(DialogInterface arg0, int arg1) {
                Toast.makeText(context,
                    "'Yes' button clicked", Toast.LENGTH_SHORT)
                    .show();
                doOnTrueResult();
            }
        });

        // set a negative/no button and create a listener
        alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {

            // do something when the button is clicked
            public void onClick(DialogInterface arg0, int arg1) {
                Toast.makeText(context, "'No' button clicked",
                Toast.LENGTH_SHORT).show();
                doOnFalseResult();
            }
        });

        // display box
        alertbox.show();
    }
}

【讨论】:

  • 谢谢先生,这将是执行此任务的适当方式。
【解决方案2】:

这就是我一直以来处理对话框数据的方式

alertbox.setPositiveButton("Yes",
    new DialogInterface.OnClickListener() {

        // do something when the button is clicked
        public void onClick(DialogInterface arg0, int arg1) {
            Toast.makeText(context,
                "'Yes' button clicked", Toast.LENGTH_SHORT)
                .show();
               myFunction(item);
        }
    });

private void myFunction(int result){
// Now the data has been "returned" (that's not
// the right terminology)
}

同样,为其他按钮使用另一个功能

【讨论】:

    【解决方案3】:

    如果函数

    public Boolean showConfirmationBox(String messageToShow, final Context context)
    

    需要在主线程中调用,你不能这样做。您永远不会在主线程上等待用户输入。这将导致 ANR。

    如果该函数可以在后台线程中调用,您可以向主线程发送消息以显示警告框,然后等待结果。善用“Handler”。

    【讨论】:

      【解决方案4】:

      你不能这样做,但你可以创建一个布尔变量,如果是,则存储 true,如果不是,则存储 False,然后你可以相应地使用该变量

      【讨论】:

        【解决方案5】:

        为结果值创建一个setter,并将该值更改为onClick() 方法中的选定值。

        使showConfirmationBox void ;-)

        【讨论】:

          【解决方案6】:

          您必须将值从 onClickListener 传递给 全局变量 或其他方法。 正如您已经正确识别出onClickListener 的返回类型是void。 如需更复杂的解决方案,请查看this post

          【讨论】:

            【解决方案7】:

            一种简单的方法:

            public class MainActivity extends Activity {
                public static boolean result;
            
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_main);
            
                    showConfirmationBox("Are you sure you want to do this", this);
            
                }
            
                public Boolean showConfirmationBox(String messageToShow, final Context context) {
                    AlertDialog.Builder alertbox = new AlertDialog.Builder(context);
                    alertbox.setMessage(messageToShow);
                    alertbox.setPositiveButton("Yes",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface arg0, int arg1) {
                            Toast.makeText(context, "'Yes' button clicked", Toast.LENGTH_SHORT).show();
                            MainActivity.result = true;
                        }
                    });
            
                // set a negative/no button and create a listener
                alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
            
                    // do something when the button is clicked
                    public void onClick(DialogInterface arg0, int arg1) {
                        Toast.makeText(context, "'No' button clicked",
                        Toast.LENGTH_SHORT).show();
                        MainActivity.result = false;
                    }
                });
            
                // display box
                alertbox.show();
            
                }
            }
            

            【讨论】:

            • 将其设为公共静态变量。从其他活动调用此代码是否已经工作?
            • 其实,光看它,它看起来就是这样。所以,是的:public static boolean result; 应该可以工作。
            【解决方案8】:

            其中一个选项是使用

            public Button getButton (int whichButton)
            Gets one of the buttons used in the dialog.
            
            this Returns
            The button from the dialog, or null if a button does not exist.
            

            更多信息请查看链接http://developer.android.com/reference/android/app/AlertDialog.html

            【讨论】:

              【解决方案9】:

              这可能对你有帮助

              public class MainActivity extends Activity {
                   Boolean mresult;
              
                  @Override
                  protected void onCreate(Bundle savedInstanceState) {
                      super.onCreate(savedInstanceState);
                      setContentView(R.layout.activity_main);
              
                        Boolean result = showConfirmationBox("Are you sure you want to do this",this);
                        Toast.makeText(getApplicationContext(), ""+result, Toast.LENGTH_LONG).show();
              
              
                  }
              
                   public Boolean showConfirmationBox(String messageToShow, final Context context) {       
              
                          AlertDialog.Builder alertbox = new AlertDialog.Builder(context);
                          // set the message to display
                          alertbox.setMessage(messageToShow);
                          // set a positive/yes button and create a listener
                          alertbox.setPositiveButton("Yes",
                          new DialogInterface.OnClickListener() {
                              // do something when the button is clicked
                              public void onClick(DialogInterface arg0, int arg1) {
                                  Toast.makeText(context,
                                      "'Yes' button clicked", Toast.LENGTH_SHORT)
                                      .show();
              
                                  mresult = true;
                              }
                          });
                          // set a negative/no button and create a listener
                          alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
                              // do something when the button is clicked
                              public void onClick(DialogInterface arg0, int arg1) {
                                  Toast.makeText(context, "'No' button clicked",
                                  Toast.LENGTH_SHORT).show();
              
                                  mresult = false;
                              }
                          });
                          // display box
                          alertbox.show();
                          return mresult;
                      }
              
              
              }
              

              【讨论】:

              • 你测试过这段代码吗?它不会像预期的那样工作,因为return mresult会在对话框显示后立即执行,而不是等待任何按钮被按下,因此总是返回false。 alert box.show()不是阻塞/模态。
              • @AleksG 此处代码中的右键需要单击工具来执行它
              • 我不确定我是否理解您的评论。我强烈建议您将代码复制/粘贴到项目中并进行测试。
              猜你喜欢
              • 2014-07-31
              • 2017-09-04
              • 1970-01-01
              • 2013-08-05
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多