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>
运行
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!