Help us understand the problem. What is going on with this article?

DrawableのResource IDをURL(String)に変換する

More than 3 years have passed since last update.

DrawableはそのままImageViewにセットすることができますが、Picassoを使ってネットワーク上の画像のURLとDrawableを同じようにStringとして扱いたいような場合、ResourceIDをURLのStringに変換できると便利です。

次のコードで実現できます。

public static String convertUrlFromDrawableResId(Context context, int drawableResId) {
    StringBuilder sb = new StringBuilder();
    sb.append(ContentResolver.SCHEME_ANDROID_RESOURCE);
    sb.append("://");
    sb.append(context.getResources().getResourcePackageName(drawableResId));
    sb.append("/");
    sb.append(context.getResources().getResourceTypeName(drawableResId));
    sb.append("/");
    sb.append(context.getResources().getResourceEntryName(drawableResId));
    return sb.toString();
    // Uriに変換したい時は Uri.parse(sb.toString())
}
konifar
親方!空からどらえもんが!
http://konifar.hatenablog.com
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away