何谓“对话框”,即当我们随便点开一个APP应用,需要显示一个进度条或需要用户对信息进行确认时,系统会弹出一个提醒用户的页面,常见的对话框有:通知对话框、带单选项列表对话框、多选项列表对话框、进度对话框。
01.创建对话框通知
public void click1(View view) {
AlertDialog.Builder builder = new Builder(this);
builder.setTitle("工学1号馆");
builder.setIcon(R.drawable.ic_launcher);
builder.setMessage("浏览wuyudong的博客?");
builder.setPositiveButton("确定", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Uri uri = Uri.parse("http://www.wuyudong.com/");// 打开链接
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
builder.setNegativeButton("取消", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
02.创建带单选项列表的对话框
public void click2(View view) {
AlertDialog.Builder builder = new Builder(this);
builder.setTitle("单选对话框");
final String[] items = new String[] { "java", ".net", "php" };
builder.setSingleChoiceItems(items, 0, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, items[which] + "被点击了", 0)
.show();
}
});
builder.show();
}
03.创建带多选项列表的对话框
public void click3(View view) {
AlertDialog.Builder builder = new Builder(this);
builder.setTitle("多选对话框");
final String[] items = new String[] { "java", ".net", "php", "C++" };
builder.setMultiChoiceItems(items, new boolean[] { true, false, false,
true }, new OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
Toast.makeText(MainActivity.this, items[which] + isChecked, 0)
.show();
}
});
builder.setNegativeButton("取消", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
04.进度对话框(ProgressDialog)
使用代码ProgressDialog.show(ProgressDialogActivity.this, "请稍等", "数据正在加载中...", true);创建并显示一个进度对话框。
调用setProgressStyle()方法设置进度对话框风格。有两种风格:ProgressDialog.STYLE_SPINNER 旋体进度条风格 (为默认风格)ProgressDialog.STYLE_HORIZONTAL 横向进度条风格
public void click4(View view) {
ProgressDialog pd = new ProgressDialog(this);
pd.setTitle("提醒");
pd.setMessage("正在加载中......");
pd.show();
}
下面的代码实现横向进度条风格:
public void click5(View view) {
final ProgressDialog pd = new ProgressDialog(this);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMax(100);
pd.show();
new Thread() {
public void run() {
for (int i = 0; i
pd.setProgress(i);
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
pd.dismiss();
};
}.start();
}
达牛是手机应用学开创者,专注于手机应用开发,参与更多的手机应用项目开发,编程技术当然比大学院校毕业生更牛。
转发本文并关注达牛微信号 todaniu 可以免费参加手机应用项目实战。