简单对话框
// 1. 创建AlertDialog 构造器 AlertDialog.Builder builder = new AlertDialog.Builder(MoreActivity.this); // 设置dialog的组成部分 builder.setIcon(R.drawable.more_delete);//图标 builder.setTitle("温馨提示");//标题 // 2. 设置内容 builder.setMessage("确定要清空数据嘛?"); // 3. 设置点击按钮 builder.setPositiveButton("否", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // 点击逻辑 } }); builder.setNegativeButton("是", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // 不退出 finish(); } }); // 4. 组合各部分后显示 builder.create().show();
多选对话框
id=0; final int [] col={Color.RED,Color.YELLOW,Color.GREEN,Color.BLUE,Color.WHITE,Color.BLACK}; final String []s={"红色","黄色","绿色","蓝色","白色","黑色"}; AlertDialog.Builder DanItem = new AlertDialog.Builder(PaintActivity.this); DanItem.setTitle("选择想要使用的颜色"); DanItem.setSingleChoiceItems(s, -1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { id =which; } }); DanItem.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which){ //点击事件 } }); DanItem.create().show();
自定义对话框
dialog.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <EditText android:id="@+id/dialog_et" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>
JAVA代码
AlertDialog.Builder customizeDialog = new AlertDialog.Builder(getContext()); final View dialogView = LayoutInflater.from(getContext()) .inflate(R.layout.dialog,null);//适配自己写的页面 customizeDialog.setTitle("请输入内容");//标题 customizeDialog.setView(dialogView);//设置页面展示 //设置按钮和点击事件 customizeDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // 获取EditView中的输入内容 EditText edit_text = (EditText) dialogView.findViewById(R.id.dialog_et); Toast.makeText(getContext(), edit_text.getText().toString(), Toast.LENGTH_SHORT).show(); String bz=edit_text.getText().toString(); System.out.println(bz); accountData.setBz(bz); tv_bz.setText(bz); } }); customizeDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.cancel(); } }); customizeDialog.show();