我一直在寻找试图弄清楚如何创建一个有 4 个选项可供选择的弹出窗口或对话框。
我在 Android 开发者网站上看到了这张图片:
有谁知道如何编写类似右边的代码?我的文本旁边不需要任何图标,我只需要能够从 4 个选项中进行选择。
您可以使用要在其中显示的选项创建一个String
数组,然后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 上):
(不包括背景图。;))
尝试这个 :
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();
}
弹出窗口只不过是AlertDialog
。所以你只需要创建AlertDialog
,然后使用膨胀你想要的视图并使用方法LayoutInflater
设置膨胀视图setView()
AlertDialog
替代选择
这是我的第一篇文章,所以我很高兴分享我的代码!这对我有用:
将这两行放在 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();