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

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

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

enter image description here

有人知道如何编写像右边这样的代码吗?我不需要任何图标旁边的文字,我只需要能够从4个选项中选择。

104922 次浏览

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

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

举个例子:

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

(不包括背景图)

试试这个:

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();
}

备选方案

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

将这两行放在 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();