示例2 Handler操作进度条
在Android布局文件中添加ProgressBar Button,并设置属性、参数
创建Handler对象,以匿名内部类的方式,重写Handler对象的handlerMessage(Message msg)方法
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//
int t = msg.arg1;
progressBar.setProgress(t);
handler.post(proThread);
// 标记2 详见后面解释
if (t == 100) {
handler.removeCallbacks(proThread);
}
super.handleMessage(msg);
}
};
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//
int t = msg.arg1;
progressBar.setProgress(t);
handler.post(proThread);
// 标记2 详见后面解释
if (t == 100) {
handler.removeCallbacks(proThread);
}
super.handleMessage(msg);
}
};
Button 的监听器
handlerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
progressBar.setVisibility(View.VISIBLE);
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
progressBar.setVisibility(View.VISIBLE);
//将要执行的线程对象放入到队列当中
handler.post(proThread); //proThread 匿名内部类方式创建的Runnable对象
}
});
创建Runnable对象
// 进度条线程 使用匿名内部类
Runnable proThread = new Runnable() {
int i = 0;//进度条的值
@Override
public void run() {
// TODO Auto-generated method stub
i = i + 10;
System.out.println("ProBar Thread_" + i);
// 得到消息对象
Message msgMessage = handler.obtainMessage();
msgMessage.arg1 = i; //设置成员变量arg1
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}
handler.sendMessage(msgMessage);
// 无法删除 不清楚原因,在 标记2 处删除
if (i == 100) {
handler.removeCallbacks(proThread);
}
}
};
Runnable proThread = new Runnable() {
int i = 0;//进度条的值
@Override
public void run() {
// TODO Auto-generated method stub
i = i + 10;
System.out.println("ProBar Thread_" + i);
// 得到消息对象
Message msgMessage = handler.obtainMessage();
msgMessage.arg1 = i; //设置成员变量arg1
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}
handler.sendMessage(msgMessage);
// 无法删除 不清楚原因,在 标记2 处删除
if (i == 100) {
handler.removeCallbacks(proThread);
}
}
};