Mark Cooper
Mark Cooper

Reputation: 6884

Get a dynamic list of Images

I'm following the Android Hello-GridView tutorial, and would like to use a dynamic list of images, from my res/drawable folder rather than a hard coded array as suggested:

// 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
};

How can I loop and load these images dynamically?

Upvotes: 0

Views: 908

Answers (2)

Kevin Coppock
Kevin Coppock

Reputation: 134664

Try using the assets folder for this instead of defining them as resources. Just dump the images into a folder under res/assets (for this example, res/assets/images). The following code should then get a list of the files in that folder:

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

Then, just set the drawable with the code @Jack Smartie posted above:

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

Where 'i' is the index of the drawable you want.

Upvotes: 1

Jack Smartie
Jack Smartie

Reputation: 443

Update: Oops, I didn't read your question as carefully as I should have. I'm not sure how you would dynamically load the resources in your drawable folder other than hard coding it into an array.

Hello,

I've done something similar in my app.

Look in the getView method of your ImageAdapter class. Within the if (view == null) portion of your code, before the else, use one of the ImageView's setters (such as setImageBitmap, setImageDrawable, setBackground, etc.).

I forgot to mention that you'll need to create a string array that holds the filepath of your images.

In my code, this is the line that I have:

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

Upvotes: 0

Related Questions