如何在启用 Button 的同时显示/开始倒计时?

“如何在启用 Button 的同时进行 CountDown 显示?”


关于按钮的附加信息:按钮作业是通过 Textview 中显示的字符串数组单击 5 次,然后禁用 5 秒钟以再次执行相同的任务。


所以..我想要一个倒计时来直观地显示那些 5 秒(按钮启用的时间)倒计时供用户查看。


遗憾的是,我不知道如何将我的 Button 与 CountDown 连接起来,让它知道它应该在启用 Button 的特定时间倒计时。


此外,我希望每次启用按钮时都开始倒计时。


我查看了https://developer.android.com/reference/android/os/CountDownTimer 但它似乎没有针对该特定情况的解决方案。


这就是我现在的按钮代码:


next_button.setOnClickListener(new View.OnClickListener() {

        @Override

        public void onClick(View v) {


            if (currentnumber == list.length) {

                currentnumber = 0;

            }

            if (Curclicks == mod - 1) {

                next_button.setEnabled(false);

                display.setText(list[currentnumber]);

                currentnumber++;



                handler.postDelayed(new Runnable() {

                    @Override

                    public void run() {

                        //the button will unlock after the delay specified

                        next_button.setEnabled(true);

                        Curclicks = 0;


                    }

                }, delay);


            } else {

                display.setText(list[currentnumber]);

                currentnumber++;


            }

            Curclicks++;


        }


    });

UI Thread 代码可以解决吗?:


  private void runThread() {


            new Thread() {

                public void run() {

                    while (delay == 5000) { //delay = 5000 ( 5 secs)

                        try {

                            runOnUiThread(new Runnable() {


                                @Override

                                public void run() {

                                    timer.setText("" + delay);//timer=TxtView

                                }

                            });

                            Thread.sleep(300);

                        } catch (InterruptedException e) {

                            e.printStackTrace();

                        }

                    }

                }

            }.start();


猛跑小猪
浏览 289回答 3
3回答

慕的地10843

下面是一个示例,说明如何使用 的postDelayed()方法Handler创建倒计时。我特意把代码留得有点冗长,这样你就可以一步一步地浏览它,看看发生了什么。创建一些类变量和常量。private static final long COUNT_DOWN_TICKS = 100l;private static final long COUNT_DOWN_FINISH = 5000l;private long countdownElapsed = 0l;private Handler mCountDownHandler = new Handler();COUNT_DOWN_FINISH设置为 5000 --> 5 秒。但可以更改为您需要的任何内容。我还使用COUNT_DOWN_TICKSset 为 100 --> 0.1 秒,以防万一您想显示更精确的倒计时。从您的OnClick()方法中只需调用startCountDown()即可开始倒计时。private void startCountDown() {    try {        countdownElapsed = 0l;        next_button.setEnabled(false);        displayCountDown();        mCountDownHandler.postDelayed(mCountDownRunnable, COUNT_DOWN_TICKS);    }    catch (Exception ex){        Log.e(TAG, ex.getMessage());    }}private Runnable mCountDownRunnable = new Runnable() {    @Override    public void run() {        countdownElapsed = countdownElapsed + COUNT_DOWN_TICKS;        if(countdownElapsed >= COUNT_DOWN_FINISH){            releaseCountDownHandler();            next_button.setEnabled(true);        }        else{            mCountDownHandler.postDelayed(mCountDownRunnable, COUNT_DOWN_TICKS);        }        long secFull = countdownElapsed % 1000;        if(secFull == 0){            runOnUiThread(new Runnable() {                @Override                public void run() {                    displayCountDown();                }            });        }    }};private void releaseCountDownHandler() {    try {        if(mCountDownRunnable != null) {            mCountDownHandler.removeCallbacks(mCountDownRunnable);        }    }    catch (Exception ex){        Log.e(TAG, ex.getMessage());    }}private void displayCountDown(){    long t = (COUNT_DOWN_FINISH - countdownElapsed)/1000;    String myTime = String.valueOf(t);    timer.setText(myTime);}为了Runnable正确处理,您需要releaseCountDownHandler()从onPause()方法中调用。这只是一个短暂的运行Thread,但它仍然不应该被忽视。我更喜欢HandlerwithpostDelay()方法而不是Thread.sleep()方法——让任何线程进入睡眠状态的事情令人不安。另请注意,习惯于使用“>=”而不是“==”检查经过时间条件是个好主意,具体取决于实现(例如,您SystemClock.elapsedRealtime()改为使用)条件可能会错过确切的值!编辑在您的Activity类定义下的某处(在本例中,我将称之为MainActivity)您需要声明一些变量。由于它们是在类内部而不是在方法内部定义的,因此它们被称为“类变量”,并且在定义为“私有”时具有整个类的范围。public class MainActivity extends AppCompatActivity {    //class variables    private static final long COUNT_DOWN_TICKS = 100l;    private static final long COUNT_DOWN_FINISH = 5000l;    private long countdownElapsed = 0l;    private Handler mCountDownHandler = new Handler();    private Button next_button;    private TextView timer;....    }您可能已经在类onClick()的onCreate()方法中声明了该方法MainActivity。所以只需添加以下代码:next_button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {    startCountDown();}我提供的所有其他方法都是MainActivity类中的方法……而不是任何其他方法中的方法。所以在onCreate()方法下面添加我之前发布的所有方法。它看起来像这样:public class MainActivity extends AppCompatActivity {    private static final String TAG = MainActivity.class.getSimpleName();    //class variables    private static final long COUNT_DOWN_TICKS = 100l;    private static final long COUNT_DOWN_FINISH = 5000l;    private long countdownElapsed = 0l;    private Handler mCountDownHandler = new Handler();    private Button next_button;    private TextView timer;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        // you must compensate for the actual layout for your activity        setContentView(R.layout.activity_main);        // you must compensate for the actual id of the TextView        timer = findViewById(R.id.tvTimer);        // you must compensate for the actual id of the Button        next_button = findViewById(R.id.btnNext);        next_button.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                startCountDown();            }        });    }    private void startCountDown() {        try {            countdownElapsed = 0l;            next_button.setEnabled(false);            displayCountDown();            mCountDownHandler.postDelayed(mCountDownRunnable, COUNT_DOWN_TICKS);        }        catch (Exception ex){            Log.e(TAG, ex.getMessage());        }    }    private Runnable mCountDownRunnable = new Runnable() {        @Override        public void run() {            countdownElapsed = countdownElapsed + COUNT_DOWN_TICKS;            if(countdownElapsed >= COUNT_DOWN_FINISH){                releaseCountDownHandler();                next_button.setEnabled(true);            }            else{                mCountDownHandler.postDelayed(mCountDownRunnable, COUNT_DOWN_TICKS);            }            long secFull = countdownElapsed % 1000;            if(secFull == 0){                runOnUiThread(new Runnable() {                    @Override                    public void run() {                        displayCountDown();                    }                });            }        }    };    private void releaseCountDownHandler() {        try {            if(mCountDownRunnable != null) {                mCountDownHandler.removeCallbacks(mCountDownRunnable);            }        }        catch (Exception ex){            Log.e(TAG, ex.getMessage());        }    }    private void displayCountDown(){        long t = (COUNT_DOWN_FINISH - countdownElapsed)/1000;        String myTime = String.valueOf(t);        timer.setText(myTime);     }   }

繁星淼淼

这段代码就像我上面的代码,除了这段代码引入了一个“点击计数器”。我引入了一个新的类变量来跟踪按钮被点击的次数。我还引入了一个名为“NUMBER_OF_BUTTON_CLICKS”的新常量,它作为点击次数的上限。用户现在可以点击按钮(在本例中)5 次。第 5 次单击时,满足触发startCountDown方法的条件并且按钮被禁用 5 秒。public class MainActivity extends AppCompatActivity {    //Constant values        private static final String TAG = MainActivity.class.getSimpleName();    private static final int NUMBER_OF_BUTTON_CLICKS = 5;    private static final long COUNT_DOWN_TICKS = 100l;    private static final long COUNT_DOWN_FINISH = 5000l;    //class variables    private int howManyClicks = 0;    private long countdownElapsed = 0l;    private Handler mCountDownHandler = new Handler();    private Button next_button;    private TextView timer;    private TextView clicks;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        // you must compensate for the actual layout for your activity        setContentView(R.layout.activity_main);        // you must compensate for the actual id of the TextView        timer = findViewById(R.id.tvTimer);        // Use this only if you want to display the number of clicks         // you might need to add this TextView if you want to display the number of clicks        clicks = findViewById(R.id.tvClicks);        // you must compensate for the actual id of the Button        next_button = findViewById(R.id.btnNext);        next_button.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                howManyClicks++;                if(howManyClicks >= NUMBER_OF_BUTTON_CLICKS){                    startCountDown();                }                //Add this only if you want to see how many clicks were made                String myClicks = String.valueOf(howManyClicks);                clicks.setText(myClicks)            }        });    }    private void startCountDown() {        try {            countdownElapsed = 0l;            next_button.setEnabled(false);            displayCountDown();            mCountDownHandler.postDelayed(mCountDownRunnable, COUNT_DOWN_TICKS);        }        catch (Exception ex){            Log.e(TAG, ex.getMessage());        }    }    private Runnable mCountDownRunnable = new Runnable() {        @Override        public void run() {            countdownElapsed = countdownElapsed + COUNT_DOWN_TICKS;            if(countdownElapsed >= COUNT_DOWN_FINISH){                releaseCountDownHandler();                next_button.setEnabled(true);                // reset the clicks counter                howManyClicks = 0;            }            else{                mCountDownHandler.postDelayed(mCountDownRunnable, COUNT_DOWN_TICKS);            }            long secFull = countdownElapsed % 1000;            if(secFull == 0){                runOnUiThread(new Runnable() {                    @Override                    public void run() {                        displayCountDown();                    }                });            }        }    };    private void releaseCountDownHandler() {        try {            if(mCountDownRunnable != null) {                mCountDownHandler.removeCallbacks(mCountDownRunnable);            }        }        catch (Exception ex){            Log.e(TAG, ex.getMessage());        }    }    private void displayCountDown(){        long t = (COUNT_DOWN_FINISH - countdownElapsed)/1000;        String myTime = String.valueOf(t);        timer.setText(myTime);        //Add this only if you want to see how many clicks were made        String myClicks = String.valueOf(howManyClicks);        clicks.setText(myClicks)    }   }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java