我正在使用一个警告对话框,显示应用程序开头的菜单,我希望对话框显示2个来自对象的“名称”值,这里是警告对话框的代码:
public void showDialog() {
EntityType en = new EntityType();
ArrayList array = ApplicationController.entities;
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick one");
builder.setItems(array, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// I want to write my code here
}
});
builder.show();
}
EntityType
是我的对象,其中包含字符串“name”,ApplicationController.entities
包含数组
答案 0 :(得分:3)
尝试以下代码..它适用于我...... :)
AlertDialog.Builder builderSingle = new AlertDialog.Builder(MainActivity.this);
builderSingle.setIcon(R.drawable.green_tick_add);
builderSingle.setTitle("Choose..");
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.select_dialog_item);
arrayAdapter.add("Change Photo");
arrayAdapter.add("Remove Photo");
builderSingle.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String strName = arrayAdapter.getItem(which);
}
});
builderSingle.show();
答案 1 :(得分:2)
public void showDialog() {
EntityType en = new EntityType();
ArrayList array = ApplicationController.entities;
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick one");
ArrayList<String> displayValues=new ArrayList<>();
for (Entity entity : array) {
displayValues.add(entity.name);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,array);
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick one");
builder.setSingleChoiceItems(displayValues, 0, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Entity selectedItem = array[which];
}
});
builder.show();
}
答案 2 :(得分:1)
ArrayAdapter<String> adapt = new ArrayAdapter<String>(this, android.R.layout.select_dialog);
adapt.add("your entity name");
然后编辑diaolog代码:
builder.setAdapter(adapt, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
//write code here
}
});
答案 3 :(得分:0)
您必须创建一个包含EntityType名称并将其添加到其中的ArrayAdapter:
ArrayAdapter<String> adapt = new ArrayAdapter<String>(this, android.R.layout.select_dialog_singlechoice);
adapt.add("your entity name");
然后在对话框上:
builder.setAdapter(adapt, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
//Your code here
}
});
希望有所帮助