Android:创建一个具有多个选择选项的弹出窗口

时间:2013-05-05 22:02:20

标签: android menu dialog popup

我一直在寻找如何创建弹出窗口或有4个选项可供选择的对话框。

我在Android开发者网站上看到了这张图片:

enter image description here

有谁知道如何编写类似右边的内容?我的文字旁边不需要任何图标,我只需要从4个选项中选择。

4 个答案:

答案 0 :(得分:256)

您可以使用要在其中显示的选项创建CharSequence数组,然后使用方法AlertDialog.Builder将数组传递给setItems(CharSequence[], DialogInterface.OnClickListener)

一个例子:

String[] colors = {"red", "green", "blue", "black"};

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a color");
builder.setItems(colors, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        // the user clicked on colors[which]
    }
});
builder.show();

输出(在Android 4.0.3上):

Output

(不包括背景地图。;))

答案 1 :(得分:6)

弹出式窗口只是AlertDialog。所以您只需要创建AlertDialog,然后使用LayoutInflater对所需视图进行充气,并使用setView()方法设置充气视图AlertDialog

答案 2 :(得分:1)

尝试一下:

public void onClick(View v){

            final String[] fonts = {"Small", "Medium", "Large", "Huge"};

            AlertDialog.Builder builder = new AlertDialog.Builder(TopicDetails.this);
            builder.setTitle("Select a text size");
            builder.setItems(fonts, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if ("Small".equals(fonts[which])){
                        Toast.makeText(TopicDetails.this,"you nailed it", Toast.LENGTH_SHORT).show();
                    }
                    else if ("Medium".equals(fonts[which])){
                        Toast.makeText(TopicDetails.this,"you cracked it", Toast.LENGTH_SHORT).show();
                    }
                    else if ("Large".equals(fonts[which])){
                        Toast.makeText(TopicDetails.this,"you hacked it", Toast.LENGTH_SHORT).show();
                    }
                    else if ("Huge".equals(fonts[which])){
                        Toast.makeText(TopicDetails.this,"you digged it", Toast.LENGTH_SHORT).show();
                    }
                    // the user clicked on colors[which]

                }
            });
            builder.show();

}

答案 3 :(得分:0)

替代选项

这是我的第一篇文章,很高兴分享我的代码! 这对我有用:

将这两行放在OnCreate事件上方

final String[] Options = {"Red", "Blue"};
AlertDialog.Builder window;

将此代码放在将触发此事件的事件上

window = new AlertDialog.Builder(this);
window.setTitle("Pick a color");
window.setItems(Options, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        if(which == 0){
           //first option clicked, do this...

        }else if(which == 1){
           //second option clicked, do this...

        }else{
        //theres an error in what was selected
            Toast.makeText(getApplicationContext(), "Hmmm I messed up. I detected that you clicked on : " + which + "?", Toast.LENGTH_LONG).show();
        }
    }
});

window.show();