【问题标题】:AlertDialog gets a return value without a handlerAlertDialog 在没有处理程序的情况下获取返回值
【发布时间】:2010-08-24 07:18:56
【问题描述】:

我想显示一些警报对话框,因此用户必须处理一些问题(有点像向导)。

是否可以让 alertDialog 等到用户选择某些内容然后返回选择的值?

    HashMap<Integer, Question> questions = DataConnector.getCallQuestions(position);

    int nextQuestion = position;

    while(nextQuestion != 0){
        Question question = questions.get(nextQuestion);

        CharSequence[] items = (String[])question.getAnswers();

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(question.getQuestion());
        builder.setItems(items, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {

            }
        });
        AlertDialog alert = builder.create();

        //I would like to do something like this:
        nextQuestion = alert.getClickedItem();
    }

编辑。回复克里斯:

程序的执行应该等到用户选择alertDialog中的选项之一

这可能吗?

像这样:

    private int answer = 0;

    ....
    ...methode(){

    //show dialog
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(question.getQuestion());
    builder.setItems(items, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {
            CallHandleMenu.this.answer = item; //setting answer
        }
    });
    builder.create().show();

    //Here I need to know the answer (the answer should not be 0 here)

【问题讨论】:

    标签: java android return handler android-alertdialog


    【解决方案1】:

    如果您希望出现一系列 AlertDialog 框,那么最好的办法是在对话框中设置一些侦听器。

    .setPositiveButton("My Button Name", new DialogInterface.OnClickListener() {
                           public void onClick(DialogInterface dialog, int id) {
                               //do stuff like set some variables, maybe display another dialog
                           }
                   }) 
    

    请注意,我使用的是警报对话框的默认肯定按钮,您可能需要根据用户单击的内容进行更改。

    如果您要从 AlertDialog onClickListener 回调到您的 Activity 类,您可以使用 MyActivityClassName.this.myMethodOrVariableHere 来执行此操作。

    希望对您有所帮助,如果您需要更多说明,请给我留言。

    【讨论】:

    • @Berty 不要指望onClickListener 之外的答案AlertDialog。而是将其保存在那里并使用showDialog (int id)showDialog (int id, Bundle args) 启动下一个对话框,这些都是Activity 类的方法,所以CallHandleMenu.this.showDialog(args) 就是您要查找的内容
    【解决方案2】:

    我以这种方式修复它(伪代码),因为我的代码很脏:p

        activity{
            onCreate{
                makeNextQuestion(1)
            }
    
            public void nextQuestion(int questionId){
                //add string and answering buttons to layout
                btn.onClickList(){
                    onClick(View btn){
                        activity.this.nextQuestion(btn.getId());
                    }
                }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2013-05-29
      • 1970-01-01
      • 2018-12-01
      • 2019-02-15
      • 2019-08-27
      • 2019-08-10
      • 2015-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多