⒈使用
普通使用
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext()); builder.setTitle("请回答:"); builder.setMessage("你觉得蔡徐坤球技如何?"); builder.setIcon(R.drawable.icon_user); builder.setPositiveButton("棒", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(getApplicationContext(),"我看你是个智障",Toast.LENGTH_LONG).show(); } }); builder.setNeutralButton("还行", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(getApplicationContext(),"我看你视力并不怎么好",Toast.LENGTH_LONG).show(); } }); builder.setNegativeButton("垃圾", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(getApplicationContext(),"你很诚实",Toast.LENGTH_LONG).show(); } }); builder.show();
单选框形式
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext()); builder.setTitle("选择性别:"); final String[] array = new String[]{"男","女"}; builder.setItems(array, new DialogInterface.OnClickListener() { /** * * @param dialog * @param which 选中的数组索引 */ @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(getApplicationContext(),"您选中了 " + array[which],Toast.LENGTH_LONG).show(); } });
单选按钮形式
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext()); builder.setTitle("选择性别:"); final String[] array = new String[]{"男","女"}; builder.setSingleChoiceItems(array, 0, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(getApplicationContext(),"您选中了 " + array[which],Toast.LENGTH_LONG).show(); } });
默认情况下点击弹出框其他区域 弹出框将会消失,通过以下方式禁用。
builder.setCancelable(false);
默认情况下点击弹出框的选项弹出框并不会消息,通过以下方式使其消失。
@Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(getApplicationContext(),"您选中了 " + array[which],Toast.LENGTH_LONG).show(); dialog.dismiss(); }
多选
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext()); builder.setTitle("选择你的特长:"); final String[] array = new String[]{"唱歌","跳舞","编程","泡妞"}; boolean[] isSelected = new boolean[]{false,false,true,true}; builder.setMultiChoiceItems(array, isSelected, new DialogInterface.OnMultiChoiceClickListener() { /** * * @param dialog * @param which 表示点击的索引 * @param isChecked 标识当前点击的选中状态 */ @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) { Toast.makeText(getApplicationContext(),array[which] + ":" + isChecked,Toast.LENGTH_LONG).show(); dialog.dismiss(); } });
自定义布局视图展示
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext()); builder.setTitle("请先登录"); View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.layout_dialog,null); EditText etUserName = view.findViewById(R.id.et_username); EditText etPassWord = view.findViewById(R.id.et_password); Button btnLogin = view.findViewById(R.id.btn_login); builder.setView(view).show();