对话框的显示,首先在onDialogCreate(int n)中创建对话框;然后使用showDialog(int n)显示对话框。调用showDialog()将启动onDialogCreate()。
自定义对话框,需要获取Context,再加载view,Context为Activity的this,而不是getApplicationContext()获得的?Dialog dialog = new Dialog(Context contex)
基于AlertDialog的对话框:
1、定义AlertDialog.Builder builder = new AlertDialog.Builder(this) //这个this也是Activity的Context
2、设置对应的builder
·按钮类型的:setMessage(),setCancelable(),setPositiveButtton()...
·列表类型的:setItems(items,listener),需先定义final CharSequence[] items;
`单选按钮类型的:setSingleChoiceItems(items,listener),,需先定义final CharSequence[] items;
3、listener为匿名类DialogInterface.OnClickLister(),点击时
4、首先在onDialogCreate(int n)中创建对话框;然后使用showDialog(int n)显示对话框。
- 简单显示信息
AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Are you sure you want to exit?") .setCancelable(false) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { MyActivity.this.finish(); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create();
- 添加一个列表
final CharSequence[] items = {"Red", "Green", "Blue"}; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Pick a color"); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show(); } }); AlertDialog alert = builder.create();
3单选按钮对话框
final CharSequence[] items = {"Red", "Green", "Blue"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a color");
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
5、自定义对话框,
Context mContext = getApplicationContext();
Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("Custom Dialog");
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Hello, this is a custom dialog!");
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageResource(R.drawable.android);