0

Drawable[]是否可以使用 for 循环生成一个?

数组列表:

List<String> list = new ArrayList<String>();
list.add(Environment.getExternalStorageDirectory() + "/App/posters/80348-16.jpg");
list.add(Environment.getExternalStorageDirectory() + "/App/posters/83462-8.jpg");

   private Drawable[] mThumbIds = {
        Drawable.createFromPath(Environment.getExternalStorageDirectory() + "/Treevo/posters/80348-16.jpg"), Drawable.createFromPath(Environment.getExternalStorageDirectory() + "/Treevo/posters/83462-8.jpg")
};

我的想法:

for (int i = 0; i < list.size(); i++)
{

      //But what I need to do here?

}

我的目标是为GridView.

4

3 回答 3

2

你可以这样做:

File dir = Environment.getExternalStorageDirectory();
List<File> list = new ArrayList<File>();
list.add(new File(dir, "App/posters/80348-16.jpg"));
list.add(new File(dir, "App/posters/83462-8.jpg"));

List<Drawable> mThumbs = new ArrayList<Drawable>();
for (File file : list) {
    mThumbs.add(Drawable.createFromPath(file.getPath());
}

如果要检索文件夹中所有 .jpg 文件的列表,可以list这样构造:

File posterDir = new File(Environment.getExternalStorageDirectory(),
    "App/posters");
List<File> list = new ArrayList<File>();
for (File file : posterDir.listFiles()) {
    if (file.isFile() && file.getName().endsWith(".png")) {
        list.add(file);
    }
}
于 2013-10-11T18:47:05.723 回答
1

不确定它期望什么样的路径,但您可以尝试Drawable.createFromPath方法。假设您将正确的路径存储在第一个列表中,您的循环将如下所示。-

Drawable[] drawables = new Drawable[list.size()]();

for (int i = 0; i < list.size(); i++) {
    drawables[i] = Drawable.createFromPath(list.get(i));
}
于 2013-10-11T18:46:04.733 回答
0

您需要做的是 for each 循环。它是这样的。

List<String> list = new ArrayList<String>();
String[] imgPathList = ... // Add all of the "/App/poster..." strings here

for(String x : imgPathList) {
  list.add(Enviroment.getExternalStorageDirectory() + x);
}

这是一个不同的例子。

List<String> list = new ArrayList<String>();
String[] data = {
    "123",
    "456",
    "789"
};

for(String x : data) {
    list.add("Number: " + x);
}

System.out.println(list.toString());

打印:“[编号:123,编号:456,编号:789]”

于 2013-10-11T18:49:58.243 回答