Android用户界面之(Dialog)对话框
在Android中,启动一个对话框有三种方式:
1、定义一个新的activity,并将其主题设置为对话框风格
2、使用AlertDialog类,并且显示它
3、使用 Android的Dialog类的子类,并且显示它
现在学习AlertDialog.Builder创建各种形式的对话框。
首先,看看启动界面如下:
用土司来显示效果,因为多次用到,所以将其抽象为一个方法。
- protected void showToast(String string) {
- Toast.makeText(this, string, Toast.LENGTH_SHORT).show();
- }
1、点击第一个按钮后,出现如下对话框:
对于这个对话框,我们用到了AlertDialog.Builder类的几个方法:
setTitle:设置标题
setIcon:设置图标
setMessage:设置文本
setPositiveButton:设置第一个按钮
setNeutralButton:第二个按钮
setNegativeButton:第三个按钮
本段代码如下:
- public void onClick(View v) {
- switch (v.getId()) {
case R.id.button1:
new AlertDialog.Builder(this)
.setTitle("这是一个最简单的对话框")
.setIcon(R.drawable.img1)
.setMessage("你好!!!")
.setPositiveButton("开始", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
DialogActivity.this.showToast("你点击了开始按钮 "+ which);
}
})
.setNeutralButton("暂停", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
DialogActivity.this.showToast("你点击了暂停按钮 "+ which);
}
})
.setNegativeButton("退出", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
DialogActivity.this.showToast("你点击了退出按钮 " + which);
}
}).show();
break;
评论暂时关闭