سؤال

I parse image name by json, and now for displaying I would have to get the drawable id by the image name so I can do this:

background.setBackgroundResource(R.drawable.eventimage1);

When I get the image name the format is like this:

image_ev1.png
هل كانت مفيدة؟

المحلول

Use this function to get a drawable when you have the image name. Note that the image name does not include the file extension.

public static Drawable GetImage(Context c, String ImageName) {
        return c.getResources().getDrawable(c.getResources().getIdentifier(ImageName, "drawable", c.getPackageName()));
}

then just use setBackgroundDrawable method.

If you only want the ID, leave out the getDrawable part i.e.

return c.getResources().getIdentifier(ImageName, "drawable", c.getPackageName());

نصائح أخرى

this gets you your image id

    int resId = getResources().
getIdentifier(your_image_name.split("\\.")[0], "drawable", getApplicationInfo().packageName);   

if you need a drawable after that :

getResources().getDrawable(resId)

Add this method to your code:

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

Then retrieve your image so:

Context ctx = getApplicationContext();
background.setBackgroundResource(getResourceID("image_ev1", "drawable", ctx)));

For Kotlin programmer (ContextCompat from API 22):

 var res = context?.let { ContextCompat.getDrawable(it,resources.getIdentifier("your_resource_name_string", "drawable", context?.getPackageName())) }

Your can also use e.g. "mipmap" instead of "drawable" if resource is place in other location.

Here is how to do in Kotlin :

// FilePath : ../drawable/app_my_bg_drawable.xml    
// Call function as: val fileIntId = getDrawableIntByFileName(context, "app_my_bg_drawable")
fun getDrawableIntByFileName(context: Context, fileName: String): Int {
    return context.resources.getIdentifier(fileName, "drawable", context.packageName)
}

// FilePath : ../drawable/app_my_bg_drawable.xml    
// Call function as: val fileDrawable = getDrawableByFileName(context, "app_my_bg_drawable")
fun getDrawableByFileName(context: Context, fileName: String): Drawable? {
    return ContextCompat.getDrawable(context, context.resources.getIdentifier(fileName, "drawable", context.packageName))
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top