如何在AlertDialog中设置单选项?

时间:2011-10-22 17:19:53

标签: android alertdialog

我无法在AlertDialog中设置Single Choice列表或Multiple Choice List。

我尝试了以下示例,但我只得到一个带有标题的对话框,确认和取消按钮,没有列表,没有消息(我设置了!)。

以下是代码:

    protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DIALOG_DELETE_CITY:
        CharSequence[] array = {"Red", "Blue", "Yellow"}; 
        return new AlertDialog.Builder(ShowPypData.this)
            .setTitle(R.string.city_actions_delete_label)
            .setMessage(R.string.city_actions_delete_select_label)
            .setSingleChoiceItems(array, -1, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub

                    }
                })
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub

                }

            })
            .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();

                }
            }).create();
    default:
        return null;
    }

}

奇怪的是,如果我评论setSingleChoiceItems部分,我可以在对话框中看到该消息。

3 个答案:

答案 0 :(得分:41)

似乎ButtonsMessageMultiple choice items是互斥的。尝试发表评论setMessage()setPositiveButton()setNegativeButton()。没自己检查一下。

答案 1 :(得分:4)

此代码适合我

 final CharSequence[] charSequence = new CharSequence[] {"As Guest","I have account here"};

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Buy Now")
                //.setMessage("You can buy our products without registration too. Enjoy the shopping")
                .setSingleChoiceItems(charSequence, 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        utility.toast(" "+charSequence);
                    }
                })
        .setPositiveButton("Go", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show()

答案 2 :(得分:-6)

它应该是数组而不是

public void onClick(DialogInterface dialog, int array )