大家好,又见面了,我是你们的朋友全栈君。ProgressDialog
[功能]
ProgressDialog 也是一种Dialog
一般 在出现ProgressDialog 后台都会再开辟Thread 来做一些耗时的工作 我演示的是从100数到0 这段时间既不太长 不用浪费时间等待 同时 也能明显地看出效果
[代码]
1. ProgressDialog 使用
public void startProgress(){
//to start Progress
pd = ProgressDialog.show(this, "loop from 100 to 0!", "is looping...", true,
false);
//pd.setIcon(R.drawable.icon);
}
2. 开辟一个Thread来从100数到0 在数完后 关闭ProgressDialog
public class TaskLoop implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
loop(5000);
messageListener.sendEmptyMessage(TASK_LOOP_COMPLETE);
}
}
public void loop(long i){
long j = i;
while(j>0){
Log.d("tag",j+"");
j = j-1;
}
}
3. 运行该Thread
Thread loop = new Thread(new TaskLoop());
loop.start();
4.定义一个Handler 用于接受 关闭ProgressDialog 的通知
private Handler messageListener = new Handler(){
public void handleMessage(Message msg) {
switch(msg.arg1){
case TASK_LOOP_COMPLETE:
pd.dismiss();
break;
}
}
};
[所有代码]
public class MyProgressUsage extends Activity {
public final static int TASK_LOOP_COMPLETE = 0;
ProgressDialog pd;
TextView tv;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.start).setOnClickListener(new OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
startLoop();
}
});
}
public void startLoop(){
startProgress();
Thread loop = new Thread(new TaskLoop());
loop.start();
}
public class TaskLoop implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
loop(5000);
messageListener.sendEmptyMessage(TASK_LOOP_COMPLETE);
}
}
public void startProgress(){
//to start Progress
pd = ProgressDialog.show(this, "loop from 100 to 0!", "is looping...", true,
false);
//pd.setIcon(R.drawable.icon);
}
//to do some time-cost task
public void loop(long i){
long j = i;
while(j>0){
Log.d("tag",j+"");
j = j-1;
}
}
private Handler messageListener = new Handler(){
public void handleMessage(Message msg) {
switch(msg.arg1){
case TASK_LOOP_COMPLETE:
pd.dismiss();
break;
}
}
};
}
[url]http://dl.iteye.com/upload/picture/pic/52676/11cd6622-cb13-337a-bd52-007185e972c0.png[/url]
over!
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/159136.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...