如何在android中显示Alert Dialog?

时间:2012-05-24 05:13:23

标签: android android-ui android-alertdialog

我想显示带有项目列表的AlertDialog。该列表应该是二维的。按下a按钮时,应显示对话框。那我该怎么办呢?是否需要单独为警报对话框创建一个xml文件,还是应该在java代码中包含该对话框?

2 个答案:

答案 0 :(得分:3)

创建警报对话框,

public void Alert(String text, String title)
    { 
        AlertDialog dialog=new AlertDialog.Builder(context).create();
        dialog.setTitle(title);
        dialog.setMessage(text);
        if(!title.equals("") && !text.equals(""))
        {
            dialog.setButton("OK",
                    new DialogInterface.OnClickListener()
                    {
                        public void onClick(DialogInterface dialog, int whichButton)
                        {
                           //
                        }
                    });
            dialog.setButton2("Cancel",
                    new DialogInterface.OnClickListener()
                    {
                        public void onClick(DialogInterface dialog, int whichButton)
                        {
                           //
                        }
                    });
        }

        dialog.show();

    }

答案 1 :(得分:0)

为什么不创建一个对话框主题活动并弹出它而不是Dialog?

如果你坚持创建一个Dialog。这是您可以尝试的一段代码。

//Class Level Variables:
CharSequence[] items = { "Google", "Apple", "Microsoft" };
boolean[] itemsChecked = new boolean [items.length];

//Call this when you want a dialog
showdialog(0);

//override onCreateDialog
@Override
protected Dialog onCreateDialog(int id) { 
    switch (id) {
    case 0:         
        return new AlertDialog.Builder(this)
        .setIcon(R.drawable.icon)
        .setTitle("This is a dialog with some simple text...")
        .setPositiveButton("OK", new 
            DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, 
            int whichButton) 
            {
                Toast.makeText(getBaseContext(), 
                     "OK clicked!", Toast.LENGTH_SHORT).show();
            }
        })
        .setNegativeButton("Cancel", new 
            DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, 
                int whichButton) 
            {
                Toast.makeText(getBaseContext(), 
                     "Cancel clicked!", Toast.LENGTH_SHORT).show();
            }
        })            
        .setMultiChoiceItems(items, itemsChecked, new 
            DialogInterface.OnMultiChoiceClickListener() {                  
                @Override
                public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                    Toast.makeText(getBaseContext(),
                        items[which] + (isChecked ? " checked!": " unchecked!"), 
                        Toast.LENGTH_SHORT).show();
                }
            }
        )
        .create();
}

这会创建一个AlertDialog,它有一个复选框和名称.....