Android - ProgressDialog 进度对话框

创建进度对话框主要有两种方法

  • 1. 直接调用 ProgressDialog 提供的静态方法 show() 显示
  • 2. 创建 ProgressDialog 对象,再设置对话框的参数,最后调用 show() 显示

ProgressDialog 有 STYLE_HORIZONTAL 和 STYLE_SPINNER 两种样式

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private ProgressDialog pd2 = null;

private final static int MAXVALUE = 100;
private int progressStart = 0;
private int add = 0;

@SuppressLint("HandlerLeak")
final Handler hand = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 0x114514) {
//设置进度条的当前值
pd2.setProgress(progressStart);
}
if (progressStart >= MAXVALUE) {
pd2.dismiss();
}
}
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

findViewById(R.id.btn1).setOnClickListener(this);
findViewById(R.id.btn2).setOnClickListener(this);
findViewById(R.id.btn3).setOnClickListener(this);
}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn1:
ProgressDialog.show(MainActivity.this, "Loading", "少女祈祷中...", false, true);
break;
case R.id.btn2:
ProgressDialog pd1 = new ProgressDialog(MainActivity.this);
// 依次设置标题,内容
pd1.setTitle("Loading");
pd1.setMessage("思考好玩的加载提示中...");
pd1.setCancelable(true);
// 这里是设置进度条的风格, HORIZONTAL 是水平进度条, SPINNER 是圆形进度条
pd1.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd1.setIndeterminate(true);
// 调用 show() 方法将ProgressDialog显示出来
pd1.show();
break;
case R.id.btn3:
progressStart = 0;
add = 0;
pd2 = new ProgressDialog(MainActivity.this);
pd2.setMax(MAXVALUE);
pd2.setTitle("Loading");
pd2.setMessage("正在挽救纱世里...");
pd2.setCancelable(false);
pd2.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// 取消不确定性进度
pd2.setIndeterminate(false);
pd2.show();
// 新建一个线程更新进度
new Thread() {
public void run() {
while (progressStart < MAXVALUE) {
progressStart = 2 * takeTime();
hand.sendEmptyMessage(0x114514);
}
}
}.start();
break;
}
}

private int takeTime() {
add++;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
return add;
}
}

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×