大家好,又见面了,我是你们的朋友全栈君。ProgressDialog
[功能] ProgressDialog 也是一种Dialog 一般 在出现ProgressDialog 后台都会再开辟Thread 来做一些耗时的工作 我演示的是从100数到0 这段时间既不太长 不用浪费时间等待 同时 也能明显地看出效果
[代码] 1. ProgressDialog 使用
代码语言:javascript复制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
代码语言:javascript复制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
代码语言:javascript复制Thread loop = new Thread(new TaskLoop());
loop.start();
4.定义一个Handler 用于接受 关闭ProgressDialog 的通知
代码语言:javascript复制private Handler messageListener = new Handler(){
public void handleMessage(Message msg) {
switch(msg.arg1){
case TASK_LOOP_COMPLETE:
pd.dismiss();
break;
}
}
};
[所有代码]
代码语言:javascript复制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]https://img.yuanmabao.com/zijie/pic/2022/09/14/poorawfzrs2.png[/url] over!
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/159136.html原文链接:https://javaforall.cn