AlertDialog与ArrayAdapter一起使用,但不显示项目列表

4

我想创建一个 AlertDialog,它将显示一个自定义对象 Supplier 的列表。已经重写了 toString() 方法以显示描述。

AlertDialog.Builder dialog = new AlertDialog.Builder(ExampleActivity.this);
dialog.setTitle("Title");
dialog.setMessage("Message:");

final ArrayAdapter<Supplier> adapter = new ArrayAdapter<Supplier>(
        ExampleActivity.this, android.R.layout.select_dialog_singlechoice);

adapter.add(new Supplier());
adapter.add(new Supplier());
adapter.add(new Supplier());

dialog.setAdapter(adapter, new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {

    }
});
dialog.setNegativeButton("Cancel", null);
dialog.show();

从我所查看的例子中,我并没有发现这段代码有什么明显的问题。然而,当我运行它时,它并没有按预期显示供应商对象列表。我还尝试过使用AlertDialog.BuildersetItemssetSingleChoiceItems方法。有谁能看出我错在哪里了吗?

2个回答

9
事实证明你不能同时设置消息和适配器。当我删除 dialog.setMessage("Message:") 时它能够工作。

它们为什么不能一起使用,有什么想法吗? - Aharon Muallem
我认为这更多是一种设计选择。它们是互斥的,因此您只能使用其中之一。解决方法是创建一个带有TextView和ListView的布局,填充它,对其进行所需操作并使用setView方法。但我发现该方法的问题是,如果列表很大,则ListView有时会出现在屏幕外。因此,您可能需要给它一个固定的高度。希望这可以帮助到您! - Stuart Robertson
哇,我刚刚在电脑前花了一小时大喊大叫。 - gsueagle2008

1
你可以使用这个:
AlertDialog.Builder builderSingle = new AlertDialog.Builder(context);
builderSingle.setIcon(R.drawable.logobig);
builderSingle.setTitle("");

ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
  context, android.R.layout.simple_list_item_1
);

arrayAdapter.add("Customer 1 ");
arrayAdapter.add("Customer 2");

builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
  @Override
  public void onClick(DialogInterface dialog, int which) {
    switch (which) {
      case 0:
        // handle item1
      break;
      case 1:
        // item2
      break;
      case 2:
        // item3
      break;
      default:
      break;
    }
  }
});

builderSingle.show();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接