Android使用ArrayList中的值创建AlertDialog?

Ans*_*hul 6 android android-listview android-adapter android-dialog

我正在使用以下代码创建一个Dialog aleart框,其中包含来自studentNames ArrayList的列表项.我正在通过读取子文件数组创建此ArrayList.但是当此代码运行时,它只显示一个零列表项的对话框.我甚至检查了我的studentNames对于null,但它有值.根据文档我需要设置ListAdapter在对话框中显示列表项,但这也不适合我.请帮我找到问题.

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();
Run Code Online (Sandbox Code Playgroud)

Ami*_*oda 28

这是你如何实现它:

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();
Run Code Online (Sandbox Code Playgroud)

  • CharSequence [] cs = studentNames.toArray(new CharSequence [list.size()]); 这就是你可以用来做的 (27认同)