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

Cor*_*iac 95 android dialog menu popup

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

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

在此输入图像描述

有谁知道如何编码像右边那样的东西?我的文本旁边不需要任何图标,我只需要能够从4个选项中进行选择.

zbr*_*zbr 272

您可以CharSequence使用要在其中显示的选项创建数组,然后AlertDialog.Builder使用该方法将数组传递给a 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();
Run Code Online (Sandbox Code Playgroud)

输出(在Android 4.0.3上):

产量

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

  • 这里不需要`.create()`,`.show()`将返回构建器创建的对话框,然后再显示它 (5认同)
  • 非常感谢你.我真的不想为简单的文本菜单实现xml布局,并且在我偶然发现这篇文章之前找不到简单的方法. (2认同)

Nik*_*sal 7

尝试这个 :

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();
}
Run Code Online (Sandbox Code Playgroud)


Vis*_*ale 6

弹出窗口只是AlertDialog.所以你只需要创建AlertDialog,然后使用所需的视图LayoutInflater充气并使用setView()方法设置膨胀的视图AlertDialog