4

我正在做 android 测验。我想添加按钮。当我单击它更改图像或颜色并按住按钮一段时间以检查答案时,如果答案正确,则显示绿色和错误的红色。

我最后在按钮上实现了更改颜色,但我不明白如何实现处理程序来延迟:-

public class QuestionActivity extends Activity implements OnClickListener{

    private Question currentQ;
    private GamePlay currentGame;




    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.question);
        processSession();

    }
    private void processSession(){
                /**
         * Configure current game and get question
         */
        currentGame = ((CYKApplication)getApplication()).getCurrentGame();
        currentQ = currentGame.getNextQuestion();
        Button nextBtn1 = (Button) findViewById(R.id.answer1);
        nextBtn1.setOnClickListener(this);
        Button nextBtn2 = (Button) findViewById(R.id.answer2);
        nextBtn2.setOnClickListener(this);
        Button nextBtn3 = (Button) findViewById(R.id.answer3);
        nextBtn3.setOnClickListener(this);
        Button nextBtn4 = (Button) findViewById(R.id.answer4);
        nextBtn4.setOnClickListener(this);
        Button nextBtn5 = (Button) findViewById(R.id.answer5);
        nextBtn5.setOnClickListener(this);
        /**
         * Update the question and answer options..
         */
        setQuestions();

    }


    /**
     * Method to set the text for the question and answers from the current games
     * current question
     */
    private void setQuestions() {
        //set the question text from current question
        String question = Utility.capitalise(currentQ.getQuestion());
        TextView qText = (TextView) findViewById(R.id.question);
        qText.setText(question);

        //set the available options
        List<String> answers = currentQ.getQuestionOptions();
        TextView option1 = (TextView) findViewById(R.id.answer1);
        option1.setText(Utility.capitalise(answers.get(0)));

        TextView option2 = (TextView) findViewById(R.id.answer2);
        option2.setText(Utility.capitalise(answers.get(1)));

        TextView option3 = (TextView) findViewById(R.id.answer3);
        option3.setText(Utility.capitalise(answers.get(2)));

        TextView option4 = (TextView) findViewById(R.id.answer4);
        option4.setText(Utility.capitalise(answers.get(3)));


        int score = currentGame.getScore();
        String scr = String.valueOf(score);
        TextView score1 = (TextView) findViewById(R.id.score);
        score1.setText(scr);
      try{ 
         new CountDownTimer(20000, 1000) {

            public void onTick(long millisUntilFinished) {
                TextView timers = (TextView) findViewById(R.id.timers);
                timers.setText("" + millisUntilFinished / 1000);
            }

            public void onFinish() { 
                currentGame.decrementScore();
                processSession();
                   }
         }.start();
      }
      catch(Exception ex)
      {
          throw new RuntimeException(ex);
      }
        }


    @Override
    public void onClick(View arg0) {
        //Log.d("Questions", "Moving to next question");
        if(arg0.getId()==R.id.answer5)
        {
        new AlertDialog.Builder(this).setMessage("Are you sure?").setCancelable(true).setPositiveButton("Yes",new DialogInterface.OnClickListener() {


        public void onClick(DialogInterface dialog,int id) {
                finish();
                 }
             }).setNegativeButton("No", null).show();

                }

        else
        {

            if(!checkAnswer(arg0)) return;  

        /**
         * check if end of game
         */
        if (currentGame.isGameOver()){
            //Log.d("Questions", "End of game! lets add up the scores..");
            //Log.d("Questions", "Questions Correct: " + currentGame.getRight());
            //Log.d("Questions", "Questions Wrong: " + currentGame.getWrong());
            Intent i = new Intent(this, EndgameActivity.class);
            startActivity(i);
            finish();
        }
        else{
            Intent i = new Intent(this, QuestionActivity.class);
            startActivity(i);
            finish();
          }
        }
      }



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        switch (keyCode)
        {
        case KeyEvent.KEYCODE_BACK :
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }


    /**
     * Check if a checkbox has been selected, and if it
     * has then check if its correct and update gamescore
     */
    private boolean checkAnswer(View v) {
     try {
     final Button b=(Button) v;
     final String answer = b.getText().toString();
     counterTimer.cancel();
     b.setBackgroundResource(R.drawable.ans);
     b.setEnabled(false);

     //Log.d("Questions", "Valid Checkbox selection made - check if correct");


         handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                 if( (currentQ.getAnswer().equalsIgnoreCase(answer)))
                {
                    b.setBackgroundResource(R.drawable.ansgreen);
                    //Log.d("Questions", "Correct Answer!");
                    currentGame.incrementScore();
                }
                else{
                    b.setBackgroundResource(R.drawable.ansred);
                    //Log.d("Questions", "Incorrect Answer!");
                    currentGame.decrementScore1();
                }
           }
         }, 10000000);

       } catch (Exception e) {
           e.printStackTrace();
       }
     return true;
}

任何答案都是可观的。

提前致谢

4

6 回答 6

3

我们可以这样做:

final ImageButton imageButton = (ImageButton) findViewById(R.id.imageButton);
int delaySeconds = 1;

    imageButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {

            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    // return true on correct & false on incorrect 
                    if (answerTrue())
                        // change the background to green.
                        imageButton.setBackgroundResource(R.drawable.green);
                    else
                        // change the background to red.
                        imageButton.setBackgroundResource(R.drawable.red);
                }
            }, delaySeconds * 1000);
        }
    });
于 2013-09-07T15:52:26.130 回答
2

我已经在按钮上实现了这个代码来改变按钮的颜色。希望它对你有用。

  private boolean checkAnswer(View v) {

            Button b=(Button) v;
            String answer = b.getText().toString();

            b.setBackgroundResource(R.drawable.ans);

                 b.setEnabled(false);

                if (currentQ.getAnswer().equalsIgnoreCase(answer))
                {
                    b.setBackgroundResource(R.drawable.ansgreen);
                }
                else{
                    b.setBackgroundResource(R.drawable.ansred);
                }
                return true;
            }

处理程序

if (currentGame.isGameOver()){
            //Log.d("Questions", "End of game! lets add up the scores..");
            //Log.d("Questions", "Questions Correct: " + currentGame.getRight());
            //Log.d("Questions", "Questions Wrong: " + currentGame.getWrong());
            final Handler handle = new Handler();
            Runnable delay = new Runnable() {
                public void run() {

                    finish();
                    startActivity(new Intent(QuestionActivity.this, EndgameActivity.class));
                }
            };
            handle.postDelayed(delay,1000);
        }
        else
        {
            final Handler handle = new Handler();
            Runnable delay = new Runnable() {
                public void run() {

                    finish();
                    startActivity(new Intent(QuestionActivity.this, QuestionActivity.class));
                }
            };
            handle.postDelayed(delay,1000);
                  }
              }
于 2013-09-09T10:41:14.980 回答
1

您可以使用 aHandler延迟某些操作。

Handler h = new Handler();

 h.postDelayed(new Runnable() {

     @Override
     public void run() {
         // DO DELAYED STUFF
     }
 }, delaytime); // e.g. 3000 milliseconds

您在run()方法中执行的操作将在您设置的延迟时间之后执行。

于 2013-09-07T15:32:07.133 回答
1

您可以通过以下方式实现您的目标Handler并将其发布到UIThread

Imagebutton ib= (ImageButton)findViewById(R.id.YourImageButtonId); //Imagebutton default may be something different.
ib.setOnClickListener(new View.onClickListener(){
Handler h = new Handler();
 h.postDelayed(new Runnable() {

    @Override
    public void run() {
     //Put your conditions accordingly
     ib.setBackgroundResource(R.drawable.Green);     
    }
 }, delaytime); // e.g. 3000 milliseconds
});
于 2013-09-07T15:34:58.317 回答
0

http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html 你需要两个线程try(){blah blah}catch。wait() 第一个到第二个通知它在按钮上有答案 setBackgroundColor

于 2013-09-28T01:24:57.707 回答
0

首先改变你的清单包名是怎么回事?在 logcat 中看到 Null 指针异常?真的是com.xxx.xxx吗?你调用的是空的资源吗?尝试{检查答案 ...}catch ...所以在您更改颜色时产生一个新线程。

于 2013-09-28T10:31:34.900 回答