8. AlertDialog
8. AlertDialog
8.1 实现方式
AlertDialog.Builder builder = new AlertDialog.Builder(context);
构建的各种参数:
方法 含义
setIcon 添加Icon
setTitle 添加标题
setMessage 添加消息
setView 设置自定义布局
create 创建Dialog
show() 显示对话框
setPositiveButton 确定按钮
setNegativeButton 取消按钮
setNeutralButton 中间按钮
8.2 演示
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<Button
android:id="@+id/dialog_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="显示对话框"
/>
</LinearLayout>
Button dialog_btn = findViewById(R.id.dialog_btn);
dialog_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setIcon(R.mipmap.ic_launcher)
.setTitle("对话框来咯!")
.setMessage("今天天气怎么样?")
//后面两个顺序不能换
.create()
.show();
}
});
添加按钮
dialog_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setIcon(R.mipmap.ic_launcher)
.setTitle("对话框来咯!")
.setMessage("今天天气怎么样?")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
System.out.println("点击了确定");
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
System.out.println("点击了取消");
}
})
.setNeutralButton("中间", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
System.out.println("点击了中间按钮");
}
})
//后面两个顺序不能换
.create()
.show();
}
});
8.3 自定义对话框布局
dialog_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="#ffff00"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="天气很好"
/>
</LinearLayout>
运行