Android上需要倒数计时器

时间:2010-08-18 09:00:14

标签: android

以下是我在Java中讨论格式倒计时器(mm:ss)的链接:

Java console code for StopWatch/Timer?

现在我想在android的textview中显示(并更新)它。任何线索?

4 个答案:

答案 0 :(得分:12)

倒计时

您将使用TextField并使用CountDownTimer更新其内容,或在同一问题中查看Rahul的答案。

要计算

在您的活动中

import android.widget.Chronometer;

...

private Chronometer crono;

protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);

 setContentView(R.layout.screen_crono);    

 this.crono = (Chronometer) findViewById(R.id.calling_crono);

    startCrono();
}

public void startCrono() {
 crono.setBase(SystemClock.elapsedRealtime());
 crono.start();
}

要阻止它

crono.stop();

在XML Layout screen_crono

<Chronometer
    android:id="@+id/calling_crono"
 android:layout_height="wrap_content" 
 android:layout_width="wrap_content" 
    android:textStyle="bold"
 android:textSize="14sp"/>

要在TextView中设置它,我认为不可能。根据您的需要,将其放在右侧或左侧。

如果这不是您想要的,我希望它可以帮助其他人。

答案 1 :(得分:7)

您还可以使用android中的CountDownTimer类。

只需声明构造函数并使用

启动计时器
timer test=new timer(30000,1000);
在上述情况下,

onTick 会在每1000毫秒内被触发一次。您可以从此处更新TextView

class timer extends CountDownTimer
{

 public timer(long millisInFuture, long countDownInterval) 
    {
  super(millisInFuture, countDownInterval);
  // TODO Auto-generated constructor stub
 }

 @Override
 public void onFinish() 
    {


 }

 @Override
 public void onTick(long millisUntilFinished) 
    {
  // TODO Auto-generated method stub
            // Update your textview on on tick

 }

 }

答案 2 :(得分:2)

在本文中使用定时UI更新的方法它真的很棒

http://developer.android.com/resources/articles/timed-ui-updates.html

此外,您可以使用内置的Android时间类来显示您的文本,它将使您的格式更容易imo

http://developer.android.com/reference/android/text/format/Time.html

答案 3 :(得分:0)

试试这段代码......

tv = new TextView(this);
    this.setContentView(tv);

//10000 is the starting number (in milliseconds)
//1000 is the number to count down each time (in milliseconds)
MyCount counter = new MyCount(10000,1000);

counter.start();

}

//countdowntimer is an abstract class, so extend it and fill in methods
public class MyCount extends CountDownTimer
{

public MyCount(long millisInFuture, long countDownInterval) 
{
super(millisInFuture, countDownInterval);
}

public void onFinish()
{
tv.setText("Time Up!");
}

public void onTick(long millisUntilFinished) 
{
tv.setText("Time Left : " + millisUntilFinished/1000);

}
相关问题