【问题标题】:Android creating AlertDialog using values from ArrayList?Android 使用 ArrayList 中的值创建 AlertDialog?
【发布时间】:2012-10-17 14:43:04
【问题描述】:

我正在使用以下代码创建一个对话框,其中包含来自 studentNames ArrayList 的列表项。我通过读取 childfile 数组来创建此 ArrayList。但是当此代码运行时,它只显示一个带有零列表项的对话框。我什至有检查我的 studentNames 是否为 null,但其中包含值。根据文档,我需要设置 ListAdapter 以在 Dialog box 中显示列表项,但这对我也不起作用。请帮我找出问题。

ArrayList<String> studentNames  = new ArrayList<String>();
            for (File file2 : childfile) {
                studentNames.add(file2.getName());
            }

    AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle(student.getName()).setAdapter(new ArrayAdapter(context, android.R.layout.simple_list_item_1, studentNames),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {

                            switch (which) {

                               cases
                            }

                        }
                    });
            builder.create();
            builder.show();

【问题讨论】:

  • 你忘记了 setItems

标签: android android-listview android-dialog android-adapter


【解决方案1】:

这就是你实现它的方法:

final CharSequence[] items = {"1", "2", "3"};

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select");
builder.setItems(items, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int item) {
        // Do something with the selection
        dialog.dismiss();
    }
});
builder.show();

【讨论】:

  • 我想使用适配器,但我没有预定义的数组项
  • CharSequence[] cs = studentNames.toArray(new CharSequence[list.size()]);这就是你可以使用的
【解决方案2】:

我有你的问题的解决方案。所以,我可以看到您正在用一些数据填充 ArrayList studentNames。尝试以下代码,以便在 DialogBox 中显示列表。

ArrayList<String> studentNames=new ArrayList<String>();

for(File file2:childfile){

        studentNames.add(file2.getName());

}
AlertDialog.Builder builder=new AlertDialog.Builder(context);
        builder.setTitle(studentNames.toArray
        (new String[studentNames.size()]),
        new DialogInterface.OnClickListener(){

//studentName.toArray() converts the List into Array so that you can use it as Dialog List.     

        public void onClick(DialogInterface dialog,intwhich){
            switch(which){

            //cases...

            }
        }

        });
}
builder.create();
builder.show();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    • 2011-03-29
    • 1970-01-01
    相关资源
    最近更新 更多