现在来理解一下和熟悉使用一下Timer.
下面我们来看看本例要实现的效果:
下面是Demo的详细步骤:
1、建TimerDemo工程文件
2、首先在来看看布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ProgressBar android:id="@+id/myProgressBar" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_marginTop="20dp"
style="?android:attr/progressBarStyleHorizontal"/>
</LinearLayout>
3、修改TimerDemo源码如下:
package com.Leo.timerdemo;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.widget.ProgressBar;
public class TimerDemo extends Activity {
private ProgressBar mProgressBar;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
switch(msg.what) {
case 1:
int currentProgressBar = mProgressBar.getProgress() + 2;
if (currentProgressBar > mProgressBar.getMax())
currentProgressBar = 0;
mProgressBar.setProgress(currentProgressBar);
}
super.handleMessage(msg);
}
};
private TimerTask timerTask = new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
Message message = new Message();
message.what = 1;
mHandler.sendMessage(message);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer_demo);
mProgressBar = (ProgressBar) findViewById(R.id.myProgressBar);
Timer timer = new Timer();
timer.schedule(timerTask, 0, 500);
}
}
解释一下timer.schedule(timerTask, 0, 500);的第二个参数,表示表示延迟执行的时间,这里是0表示立即执行。第三个参数表示重复执行时间的间隔。
到处就已经完成。不过遇到很奇怪的问题,csdn突然贴图不了,请各位知道告诉一下怎么回事?谢谢!
本文参考:android开发完全讲义