注:记录学习启舰大神的博客,此博客只做学习总结之用。
一、标准Dialog的基本知识
首先需要创建AlertDialog.Builder对象,它是用来设置dialog的各种参数的。
1、icon、消息(Message)、标题(title)
//添加icon
builder.setIcon(R.mipmap.ic_launcher);
//添加title
builder.setTitle("退出");
//添加Message
builder.setMessage("你确定要离开吗?");
//创建Dialog
builde.create();
//显示Dialog
builder.show();
2、按钮
Dialog有三个按钮可以选择:左按钮,中间按钮和右按钮。三者的位置与代码位置无关。
builder.setPositiveButton("确定",new DialogInterface.OnClickListener());
builder.setNegativeButton("取消",new DialogInterface.OnClickListener())
builder.setNeutralButton("中间按钮",new DialogInterface.OnClickListener())
具体使用如下:
=builder.setPositiveButton("确定",new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//点击响应
Toast.makeText(MainActivity.this, "ok click", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//点击响应
Toast.makeText(MainActivity.this, "cancel click", Toast.LENGTH_SHORT).show();
}
});
builder.setNeutralButton("中间BTN", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//点击响应
Toast.makeText(MainActivity.this,"center click",Toast.LENGTH_SHORT).show();
}
});
二、自定义布局
在AlertDialog中使用builder.setView(view)可以添加我们自己定义的布局视图
1、静态构建布局
- 创建一个布局文件,比如my_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/my_view_root"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@drawable/dog"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="小狗图片"
android:textSize="30sp" />
</LinearLayout>
- 布局文件写好之后可以通过LayoutInflater获取view对象,然后通过builder.setView(view)加载到Dialog中
LayoutInflater inflater = getLayoutInflater();
View view - inflater.inflate(R.layout.my_view,false);
builder.setView(view);
2、动态构建布局
LinearLayout root_lin = new LinearLayout(MainActivity.this);
root_lin.setOrientation(LinearLayout.HORIZONTAL); //设置LInearLayout的排列方向
LinearLayout.LayoutParams LP_FW = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
root_lin.setLayoutParams(LP_FW);
ImageView imageView = new ImageView(MainActivity.this);
imageView.setImageResource(R.drawable.dog);
imageView.setLayoutParams(LP_FW);
root_lin.addView(imageView);
TextView textView = new TextView(MainActivity.this);
textView.setText("可爱的小狗");
textView.setTextSize(20);
textView.setLayoutParams(LP_FW);
root_lin.addView(textView);
首先创建一个顶层容器LinearLayout,并为其设置布局,然后创建一个ImageView用来放置图片,布局样式和父控件相同,TextView也是如此。