为了账号安全,请及时绑定邮箱和手机立即绑定

无法正确使用Handler

无法正确使用Handler

蓝山帝景 2022-06-15 09:37:30
我开始学习安卓开发。我正在构建一个基本的加法游戏,用户必须单击显示两个数字相加的按钮。有四个 Textviews。第一个给出time limit每个要回答的问题。二是给question用户。第三个给出current score用户的,最后一个给出选择的打开是正确的还是不正确的。除第一个按钮外,一切正常。每次按下按钮时,计数都会非常快。// When First button is pressedpublic void onClickButton1(View view) {        correctIncorrect.setVisibility(View.VISIBLE);        if (Integer.parseInt(button1.getText().toString())==sum) {            correctIncorrect.setText("Correct");            correctUpdater();        }        else {            correctIncorrect.setText("Incorrect");            inCorrectUpdater();        }}//Similar to all the buttons//To Update the scorepublic void correctUpdater() {        n++;        yourScore++;        score.setText(Integer.toString(yourScore) + "/" + Integer.toString(n));        update();}public void inCorrectUpdater() {    n++;    score.setText(Integer.toString(yourScore) + "/" + Integer.toString(n));    update();}// To update the timer//=======================================================================//    public void resetTimer() {        timer.setText(Integer.toString(temp)+"s");        if (temp == 0) {            inCorrectUpdater();            update();        }        else {            timeUpdater();        }    }    public void timeUpdater() {        Handler timeHandler = new Handler();        Runnable timeRunnable = new Runnable() {            @Override            public void run() {                temp--;                resetTimer();            }        };        timeHandler.postDelayed(timeRunnable,1000);    }我是否错误地使用了处理程序?我能做些什么?
查看完整描述

1 回答

?
qq_花开花谢_0

TA贡献1835条经验 获得超7个赞

我是否错误地使用了处理程序?我能做些什么?


更好的方法是CountDownTimer,通过使用它,您不必自己处理Handler并且您还可以取消正在运行的 CountDownTimer。


除第一个按钮外,一切正常


不太确定在 onClick() 中使用相同代码单击按钮时会导致不同行为的原因。但是您可以考虑对所有 4 个按钮使用相同的onClickListener,这样:


View.OnClickListener myListener = new View.OnClickListener() {

        @Override

        public void onClick(View button) {

            correctIncorrect.setVisibility(View.VISIBLE);

            if (Integer.parseInt(button.getText().toString())==sum) {

                correctIncorrect.setText("Correct");

                correctUpdater();

            }

            else {

                correctIncorrect.setText("Incorrect");

                inCorrectUpdater();

            }

        }

    };


button1.setOnClickListener(myListener);

button2.setOnClickListener(myListener);

button3.setOnClickListener(myListener);

button4.setOnClickListener(myListener);

这将确保单击 4 个按钮中的任何一个都具有相同的行为(当然取决于答案)


如果您对 CountDownTimer 上的 onTick() 方法感到困惑,您可以使用修改后的 CountDownTimer,这将确保计时器不会错过任何滴答声。


查看完整回答
反对 回复 2022-06-15
  • 1 回答
  • 0 关注
  • 249 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号