代码之家  ›  专栏  ›  技术社区  ›  Berty

AlertDialog获取不带处理程序的返回值

  •  0
  • Berty  · 技术社区  · 14 年前

    我想显示一些alertdialogs,所以用户必须处理一些问题(有点像向导)。

    是否可以让alertDialog等待用户选择某个对象,然后返回choisen值?

        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)
    
    2 回复  |  直到 13 年前
        1
  •  0
  •   smith324    14 年前

    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
                           }
                   }) 
    

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

    如果你要回电话给你的朋友 Activity 来自 onClickListener MyActivityClassName.this.myMethodOrVariableHere 这样做。

    希望这能有所帮助,如果你想进一步澄清,请给我留言。

        2
  •  0
  •   Peter Mortensen code4jhon    13 年前

    我这样修正了它(伪代码),因为我的代码太脏了: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());
                    }
                }
            }
        }