获取动态图像列表

时间:2011-05-26 21:33:19

标签: android android-layout

我正在关注Android Hello-GridView tutorial,并希望使用动态的图像列表,来自我的res / drawable文件夹而不是建议的硬编码数组:

// references to our images
private Integer[] mThumbIds = {
        R.drawable.sample_2, R.drawable.sample_3,
        R.drawable.sample_4, R.drawable.sample_5,
        R.drawable.sample_6, R.drawable.sample_7,
        R.drawable.sample_0, R.drawable.sample_1
};

如何动态循环和加载这些图像?

2 个答案:

答案 0 :(得分:1)

尝试使用assets文件夹,而不是将它们定义为资源。只需将图像转储到res / assets下的文件夹中(例如,res / assets / images)。然后,以下代码应该获取该文件夹中的文件列表:

AssetManager assets = getAssets();
String[] drawables = assets.list("images");

然后,只需使用上面发布的代码@Jack Smartie设置drawable:

imageView.setBackgroundDrawable(Drawable.createFromPath(drawables[i]))

其中'i'是您想要的drawable的索引。

答案 1 :(得分:0)

更新:哎呀,我没有仔细阅读你的问题。我不确定如何动态加载可绘制文件夹中的资源,而不是将其硬编码到数组中。

您好,

我在我的应用程序中做了类似的事情。

查看getView课程的ImageAdapter方法。在代码的if (view == null)部分内,在else之前,使用ImageView的一个setter(例如setImageBitmap,setImageDrawable,setBackground等)。

我忘了提到你需要创建一个包含图像文件路径的字符串数组。

在我的代码中,这是我的行:

imageView.setBackgroundDrawable(Drawable.createFromPath(MainActivity.imageStringArray[position]));