Answers:
您可以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上):
(不包括背景图。)
弹出窗口不过是什么AlertDialog
。因此,您只需要创建AlertDialog
,然后使用扩展所需的视图LayoutInflater
并使用的setView()
方法设置扩展的视图AlertDialog
试试这个 :
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();
.create()
在这里是不必要的,.show()
将返回由构建器创建的对话框,然后也将其显示