本例子每隔1秒更新一下进度条,是对ProgressBar的练习。
用到了Timer定时器类和TimerTask类。
关键函数:
/*timer.schedule(task, 1000, 1000);
* 用Timer对象执行TimerTask任务,
*第一个参数:task ,the task to schedule.任务
*第二个参数:delay ,amount of time in milliseconds before first execution.时间间隔
* 第三个参数:period ,amount of time in milliseconds between subsequent executions每次执行所花的时间
*/
布局文件:progressbar_layout.xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ProgressBar
android:id="@+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ProgressBar
android:id="@+id/progressBar2"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ProgressBar
android:id="@+id/progressBar3"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
AtyProgressBar.java文件:
package com.fxj.composit;
import java.util.Timer;
import java.util.TimerTask;
import com.fxj.compractice.R;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ProgressBar;
public class AtyProgressBar extends Activity {
private ProgressBar pb; // 进度条
private int progress = 0; // 进度值
private Timer timer; // Timer对象
private TimerTask task = null; // TimerTask对象
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.progressbar_layout);
pb = (ProgressBar) findViewById(R.id.progressBar3);
// 设置进度最大值100
pb.setMax(100);
}
// Activity的生命周期函数onResume中开始时间Time任务
@Override
protected void onResume() {
super.onResume();
startTime();// 开始时间任务
}
// Activity的生命周期函数onDestroy中停止时间Time任务
@Override
protected void onDestroy() {
super.onDestroy();
stopTimer();// 停止时间任务
}
// 开始时间任务,也就是每隔一定时间更新进度条
public void startTime() {
// 实例化Timer对象
timer = new Timer();
// TimerTask的run方法中更新进度值
task = new TimerTask() {
@Override
public void run() {
// 进度值每次加5
progress += 5;
// 为进度条设置进度
pb.setProgress(progress);
}
};
/*
* timer.schedule(task, 1000, 1000); 用Timer对象执行TimerTask任务,第一个参数:task
* ,the task to schedule.任务第二个参数:delay ,amount of time in milliseconds
* before first execution.时间间隔 第三个参数:period ,amount of time in
* milliseconds between subsequent executions每次执行所花的时间
*/
timer.schedule(task, 1000, 1000);
}
// 停止执行时间任务,也就是取消任务
public void stopTimer() {
// 取消任务
timer.cancel();
task.cancel();
// 对象置为空
if (timer != null)
timer = null;
if (task != null)
task = null;
}
}
运行效果:
结束。