Question

I have in my drawable folder four pictures: small_blue.jpg, small_green.jpg, big_blue.jpg and big_green.jpg

I have created a function with two parameters:

public Bitmap getPic (String size, String color)
{
   return BitmapFactory.decodeResource( getResources(), R.drawable.small_blue);
} 

I need to change small_blue in R.drawable.small_blue with the parameters of the function but I cannot do:

R.drawable. + size + "_" + color

How is it done?

Thanks a lot

Was it helpful?

Solution

Try this:

public Bitmap getPic (String size, String color)
{
    return
        BitmapFactory.decodeResource
        (
            getResources(), getResourceID(size + "_" + color, "drawable", getApplicationContext())
        );
}

protected final static int getResourceID
(final String resName, final String resType, final Context ctx)
{
    final int ResourceID =
        ctx.getResources().getIdentifier(resName, resType,
            ctx.getApplicationInfo().packageName);
    if (ResourceID == 0)
    {
        throw new IllegalArgumentException
        (
            "No resource string found with name " + resName
        );
    }
    else
    {
        return ResourceID;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top