弹出式对话框AlertDialog

Andorid中经常使用到格式对话框。如下:

1.确定对话框:


弹出式对话框AlertDialog_第1张图片
确定对话框


实现代码:

new AlertDialog.Builder(this).setTitle("确认").setMessage("确定吗?")

.setPositiveButton("是",new Alert1())

.setNegativeButton("否",null).show();


2.提示框:

弹出式对话框AlertDialog_第2张图片

代码:

dialog =new AlertDialog.Builder(this)

.setTitle("标题")

.setMessage("你登陆成功了")

.setPositiveButton("确定",null)

.show();


3.带输入框的:

弹出式对话框AlertDialog_第3张图片

代码:

editText = new EditText(this);

new AlertDialog.Builder(this)

.setTitle("请输入")

.setIcon(android.R.drawable.ic_dialog_info)

.setView(editText)

.setPositiveButton("确定",new Alert3())

.setNegativeButton("取消",null).show();


4.单选对话框:

弹出式对话框AlertDialog_第4张图片

代码:

new AlertDialog.Builder(this)

.setTitle("请选择")

.setIcon(android.R.drawable.ic_dialog_info)

.setSingleChoiceItems(new String[] {"红色","黄色","蓝色","黑色" },0, new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog,int which) {

dialog.dismiss();

Toast.makeText(MainActivity.this,"你选择了: " + which,5).show();

}})

.setNegativeButton("取消",null).show();


5.多选:

弹出式对话框AlertDialog_第5张图片


代码:

new AlertDialog.Builder(this)

.setTitle("多选框")

.setMultiChoiceItems( new String[] {"选项1","选项2","选项3","选项4"},null,null)

.setPositiveButton("确定",null)

.setNegativeButton("取消",null)

.show();


6.自定义:

弹出式对话框AlertDialog_第6张图片


view = LayoutInflater.from(this).inflate(R.layout.alert6,null);// 自定义布局

dialog=new AlertDialog.Builder(this).create();

Button leftButton = (Button) view.findViewById(R.id.bt1);

leftButton.setOnClickListener(new android.view.View.OnClickListener() {

@Override

public void onClick(View v) {

Toast.makeText(MainActivity.this,"你点击了左边按钮", Toast.LENGTH_LONG).show();

dialog.dismiss();

}

});

Button rightButton = (Button) view.findViewById(R.id.bt2);

rightButton.setOnClickListener(newandroid.view.View.OnClickListener() {

@Override

public void onClick(View v) {

Toast.makeText(MainActivity.this,"你点击了右边按钮", Toast.LENGTH_LONG).show();

dialog.dismiss();

}

});

dialog.show();

WindowManager.LayoutParams params =dialog.getWindow().getAttributes();// 得到属性

params.gravity= Gravity.CENTER;// 显示在中间

params.width= (int) (getWindowManager().getDefaultDisplay().getWidth() * 0.8);// 设置对话框的宽度为手机屏幕的0.8

params.height= (int) (getWindowManager().getDefaultDisplay().getHeight() * 0.25);// 设置对话框的高度为手机屏幕的0.25

dialog.getWindow().setAttributes(params);// 设置属性

dialog.getWindow().setContentView(view);// 把自定义view加上去

你可能感兴趣的:(弹出式对话框AlertDialog)