Ambran Ambran - 1 month ago 4x
Android Question

Android: Count strings and drawables

I'm circulating some drawable images (fx. I have a few images named image_1, image_2 etc.) as header images in a fragment. The images are loaded randomly as I hardcode the number of images available for me, and generate a random index from 0 to this number.

is a final:

private int getHeaderBackground() {
// Random index between 0 and mHeaderBackgroundImagesCount
Random rand = new Random();
int index = rand.nextInt(mHeaderBackgroundImagesCount) + 1;

return getResources()
.getIdentifier("image_" + index, "drawable", getPackageName());

As hard coding anything isn't normally the way to go in correct programming, I therefore like to dynamically find out how many 'image_X' drawables I have and set it to

I would like to do the same with strings from the
resource file as I'm also circulating some strings on every page load.

Solution Update

This update is inspired by the solutions suggested below. It includes syntax corrections and optimizations and have been tested to work.

Count strings (thanks qantik)

<string-array name="foo_array">
<item name="1">abc1</item>
<item name="2">abc2</item>
<item name="3">abc3</item>

int countStrings = getResources().getStringArray(R.array.foo_array).length;

Count drawables (thanks Lalit Poptani):

long id = -1;
int countDrawables = -1;
while (id != 0) {
id = getResources().getIdentifier("weekly_stats_bg_" + (countDrawables+1),
"drawable", getPackageName());


I am not sure if it's possible to dynamically get the number of resources or drawables.

A way to circumvent this issue is to use string arrays as resources in strings.xml.


<string-array name="foo-array"> 

int count = getResources().getStringArray(;