进度条与android中的倒计时器

时间:2012-04-21 08:48:56

标签: android-layout

我的布局中需要一个进度条,总时间为30秒,每秒都会打勾。基本上我希望我的应用程序的用户看到他在时间到来之前有30秒的时间。

这是我写的代码。 但这给了我一个没有活动的空白进度条。请帮忙。 我做错了什么

public class MySeekBarActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);    
    setContentView(R.layout.main);
    setProgressBarVisibility(true);      

    final ProgressBar progressHorizontal = (ProgressBar) findViewById(R.id.progress_horizontal);
    progressHorizontal.setProgress(progressHorizontal.getProgress()* 100);

    new CountDownTimer(30000, 1000) { 
        public void onTick(long millisUntilFinished) {              
            progressHorizontal.incrementProgressBy(1);
            int dtotal = (int) ( 30000 - millisUntilFinished ) /30000 * 100;
            progressHorizontal.setProgress(dtotal);                
        }            
        public void onFinish() {
            // DO something when 2 minutes is up
       }
   }.start();
}
}

1 个答案:

答案 0 :(得分:2)

由于两件事,你有一个类型转换错误:

  • 你要用一个int来划分,这会导致小数被向下舍入,
  • 另外,你过早地投射结果,所以即使你除以浮点数/双数,结果也会向下舍入。

要明白我的意思 - 您可以安全地从您的代码中删除强制转换为int,并且无论如何都会编译。这意味着你的最终数字是一个int,因为你之前没有进行任何演员表,这意味着你很快就会在代码中丢失小数信息。

这是一个可能的解决办法:

int dtotal = (int) (( 30000 - millisUntilFinished ) /(double)30000 * 100);

将来解决此类错误,使用包含等式的循环创建一个虚拟Java程序,并打印出中间结果,例如:

public class NumberTester {

    //define the constants in your loop
    static final int TOTAL_TIME = 30000;
    static final int INTERVAL = 1000;

    public static void main(String[] args) {

        //perform the loop
        for(int millisUntilFinished = TOTAL_TIME;millisUntilFinished >=0;millisUntilFinished -= INTERVAL) {
            int dtotal = (int) (( TOTAL_TIME - millisUntilFinished ) /(double)TOTAL_TIME * 100);
            System.out.println(dtotal);
        }

    }

}

另外,一些重要的事情:

  • 不要在 onCreate 中启动计时器 - 此时您的活动尚未显示!请改用 onResume
  • onPause 中杀死你的计时器。让计时器和线程不受管理是不好的形式,可能会导致奇怪的错误。
  • 不要使用"magic numbers"。将所有常量值放在静态最终类成员中,就像我在示例中所做的那样。当您决定更改这些值时,这将为您节省很多麻烦。

编辑:至于为什么你的进度条没有完成,这是因为 onTick 方法的工作方式与你可能假设的有所不同。要了解我的意思,请添加:

System.out.println("Milis:" + millisUntilFinished);
System.out.println("dtotal:" + dtotal);

onTick 方法。这些值显然不会倒数到0(因此在dtotal的情况下为100,它来自millisUntilFinished) - 你必须对此进行补偿。

相关问题