我正在编写我的第一个应用程序,我需要每秒更新文本视图中的数字,直到按下按钮。使用处理程序似乎是不可能的,因为数字是在处理程序之外创建和存储的,但它不能被声明为final,因为它需要更改。 Thread.sleep
似乎也会使应用程序无限期挂起,然后执行上面写的代码。
final TextView countView = (TextView) findViewById(R.id.counter);
countView.setText("100,000,000,000");
//set a Calendar object to be 00:00:00:00 on Jan 1, 2015
final Calendar startTime = Calendar.getInstance();
startTime.set(2015, 0, 0, 12, 0, 0);
startTime.set(Calendar.MILLISECOND, 0);
final Button startButton = (Button) findViewById(R.id.startButton);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//set a Calendar to be the time that the button is clicked and find the difference in ms between it and startTime
Calendar nowTime = Calendar.getInstance();
double milStart = startTime.getTimeInMillis();
double milNow = nowTime.getTimeInMillis();
double diff = (milNow-milStart)/1000; //difference in seconds between "start" date and current date
double total = 100000000000L; //# that needs to be updated
for(long i = 0L; i < diff; i++) {
total += 1.8;
}
countView.setText(NumberFormat.getInstance().format(total));
我需要每秒继续增加total
1.8或每556毫秒增加1。
while(true) {
countView.setText(NumberFormat.getInstance().format(total));
total += 1.8;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
}
单击按钮后,应用程序会无限期挂起,这样即使第一个countView.setText(NumberFormat.getInstance().format(total));
也不会执行。
使用处理程序对我来说似乎不可能,因为total
如果声明为final则无法工作,但在处理程序内创建变量并循环它会导致值永远不会改变。
我错过了一个明显的解决方案吗?这是我对Java的第一次真正的努力,所以对我来说这是全新的
答案 0 :(得分:5)
你可以使用Handler
Handler h = new Handler();
final Runnable r = new Runnable() {
int count = 0;
@Override
public void run() {
count++;
textView.setText(""+count*1.8);
h.postDelayed(this, 1000); //ms
}
};
h.postDelayed(r, 1000); // one second in ms