API表示警报对话框可以有一个,两个或三个按钮,但SDK只允许正面和负面按钮。那我怎么能添加第三个按钮呢?
答案 0 :(得分:215)
创建对话框时,请向构建器添加以下内容:
builder = new AlertDialog.Builder(context);
builder.setTitle("Test");
builder.setIcon(R.drawable.icon);
builder.setMessage("test");
builder.setPositiveButton("Call Now",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
});
builder.setNeutralButton("Setup",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
context.startActivity(new Intent(context, Setup.class));
//dialog.cancel();
}
});
builder.setNegativeButton("Exit",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
});
builder.create().show();
答案 1 :(得分:125)
此代码段应该有助于解释您可以使用的三个不同按钮:
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Dialog Button");
alertDialog.setMessage("This is a three-button dialog!");
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Button 1 Text", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//...
} });
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Button 2 Text", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//...
}});
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "Button 3 Text", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//...
}});
答案 2 :(得分:43)
添加任意数量的按钮而不使用xml:
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Title");
builder.setItems(new CharSequence[]
{"button 1", "button 2", "button 3", "button 4"},
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch (which) {
case 0:
Toast.makeText(context, "clicked 1", 0).show();
break;
case 1:
Toast.makeText(context, "clicked 2", 0).show();
break;
case 2:
Toast.makeText(context, "clicked 3", 0).show();
break;
case 3:
Toast.makeText(context, "clicked 4", 0).show();
break;
}
}
});
builder.create().show();