在Android官方網站上,提到如何利用計時功能來更新人機介面的內容。http://developer.android.com/resources/articles/timed-ui-updates.html
以下是修改自該篇文章的完整範例:
package com.example.update;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;
public class UpdateUIActivity extends Activity {
private long mStartTime;
TextView mTimeLabel;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTimeLabel = (TextView) findViewById(R.id.timer);
mStartTime = System.currentTimeMillis();
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.postDelayed(mUpdateTimeTask, 100);
}
private Handler mHandler = new Handler();
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
final long start = mStartTime;
long millis = System.currentTimeMillis() - start;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
if (seconds < 10) {
mTimeLabel.setText("" + minutes + ":0" + seconds);
} else {
mTimeLabel.setText("" + minutes + ":" + seconds);
}
mHandler.postDelayed(mUpdateTimeTask, 100);
}
};
}
沒有留言:
張貼留言