【问题标题】:How to implement decreasing counter in textView.setText using for loop?如何使用 for 循环在 textView.setText 中实现递减计数器?
【发布时间】:2021-08-10 07:30:16
【问题描述】:

我正在尝试在 android java 中使用 for 循环来实现递减计数器。我使用 handler & runnable 来延迟循环迭代,我希望计数器从 80 开始并以 0 结束,但在输出中,我得到的计数器从 0 到 80。简而言之,需要相反。

这是我的代码,

TextView totalpoints = (TextView) findViewById(R.id.txttotalpoints);
        Handler handler1 = new Handler();

        for (int count = 80;count>=0; count--){
            int finalCount = count;


            handler1.postDelayed(new Runnable() {

                @Override
                public void run() {
                    totalpoints.setText("Total Points : "+ finalCount);
                    System.out.println("This is in newpointsCounter" + finalCount);


                }
                }, 1000 * count);
        }

当前输出 => 从 0 开始,在 80 结束

需要的输出 => 从 80 开始,在 0 结束

【问题讨论】:

  • 它实际上显示的值是从 0 到 80,还是只显示 80
  • 是的,从0开始,到80结束。
  • 最好使用CountDownTimer

标签: java android for-loop counter


【解决方案1】:

您可以使用CountDownTimer 为:

CountDownTimer countDownTimer = new CountDownTimer(80000, 1000) {
    @Override
    public void onTick(long millisUntilFinished) {
        //TODO on each  interval, print your count
    }

    @Override
    public void onFinish() {
        //TODO on finish of timer, you will get notified
    }
};

countDownTimer.start();

【讨论】:

    【解决方案2】:

    试试这个:

    final Handler handler = new Handler(); 
    int count = 80;
    
    final Runnable runnable = new Runnable() {
        public void run() { 
            totalpoints.setText("Total Points : " + count);
            Log.d(TAG, "count: " + count);
            if (count-- > 80) {
                handler.postDelayed(this, 5000);
            }
        } 
    }; 
    
    handler.post(runnable);
    

    另外我会推荐使用日志标签而不是android的system.println

    【讨论】:

    • 仍然,输出从 0 开始,到 80 结束,没有任何延迟。
    【解决方案3】:
    No need to use handler, Android provides CountDownTimer itself just use it.
    
    
    // For Java
    
        new CountDownTimer(30000, 1000) {
        
            public void onTick(long millisUntilFinished) {
                
                    System.out.println( millisUntilFinished / 1000)
            }
        
            public void onFinish() {
                //work done
            }
        
        }.start();
    
    
    // For kotlin
    
    object : CountDownTimer(30000, 1000) {
                override fun onTick(millisUntilFinished: Long) {
                System.out.println( millisUntilFinished / 1000)
                }
    
                override fun onFinish() {
                }
            }.start()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-23
      相关资源
      最近更新 更多