【问题标题】:Android screen goes black on while loopAndroid屏幕在while循环时变黑
【发布时间】:2015-11-25 00:12:19
【问题描述】:

我有一个包含多项选择题的活动布局。我的目标是只需要使用一个活动,并在回答每个问题后用新的选择刷新布局。但是,我将它放在while loop 中,如下所示,我希望单选按钮的onClickListener 会停止while 循环并等待用户选择一个选项,然后相应地更新UI,而是屏幕只是变黑了。

我尝试过使用调试器,但它一进入 while 循环就停止了,但我不知道为什么。

private void play(){
        int questionCount = 1;

        while(questionCount < 20) {

            Question question = new Question();
            final Game game = new Game();
            String[] questions = new String[5];
            final int temp = questionCount;

            questions = game.getQuestions(questionCount);

            A.setText(questions[0]);
            B.setText(questions[1]);
            C.setText(questions[2]);
            D.setText(questions[3]);
            E.setText(questions[4]);

            group.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int answer = group.getCheckedRadioButtonId();
                    boolean correct = game.checkAnswer(answer, temp);

                }
            });

            questionCount++;

        }

    }

【问题讨论】:

    标签: android debugging while-loop


    【解决方案1】:

    不要使用循环,而是使用在单击其中一个单选按钮时使用新问题更新屏幕的逻辑,即屏幕应该通过来自 onClickListener 的调用而不是while 循环。

    【讨论】:

      【解决方案2】:

      Android 有自己的事件循环,因此您无需创建自己的事件循环。

      更好的实现是在 Activity 的 onCreate 方法中设置视图以显示初始问题并为回答按钮设置 OnClickListener。然后,该点击监听器可以调用一个处理答案检查和获取下一个问题的类。

      例子:

      class QuizManager {
          private int mCurrentQuestion;
          String[] mQuestions;
      
          //TODO: create constructor to initialize variables
      
          public bool checkAnswer(int answer){
              //TODO: check answer logic
              return isAnswerCorrect;
          }
      
          public String getNextQuestion(){
              mCurrentQuestion++;
              //TODO: handle the case for the last question
              return mQuestions[mCurrentQuestion];
          }
      }
      

      现在您的方法可能如下所示:

      private void play(){
      
          //This should probably be a member variable in your Activity
          QuizManager manager = new QuizManager();
      
          mQuestionTextView.setText(getNextQuestion();
      
          group.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  int answer = group.getCheckedRadioButtonId();
                  if (manager.checkAnswer(answer)){
                      mQuestionTextView.setText(getNextQuestion());
                  }
              }
          });
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多