【问题标题】:Android loading images to ImageView from drawable using only the file nameAndroid仅使用文件名将图像从drawable加载到ImageView
【发布时间】:2016-08-28 20:19:16
【问题描述】:

我需要将图像从可绘制对象加载到图像视图。 ImageView 是 ListViewItem 的一部分,因此我有大量的项目和大量的图像。

在加载时,应用会解析一个 JSON 文件,该文件说明每个列表项要加载的文件名等信息。

例如,“test_a.jpg”。

文件“test_a.jpg”位于“drawable”中。

我想在运行时加载 drawable/test_a.jpg、test_b.jpg、big_chief.jpg 等等...

 int intCurrImageResourceID = this.context.getResources().getIdentifier(strPictureName, "drawable", context.getPackageName());

关于如何实现这一目标的任何想法?

*** 编辑 **** 事实证明,您不应该使用文件扩展名。所以 image.jpg 是错误的。图像是正确的。谢谢大家。尤其是@Augusto Carmo。

【问题讨论】:

  • 当图像数量很大时,用于 Picasso 加载到图像视图中的图像。
  • 从服务器加载图像名称不是最佳做法,尽管图像存在于 Drawable 文件夹中。
  • @BhunnuBaba,我可能会使用它,但对于我的 MVP,不需要这样做。我可以使用图像名称在运行时获取资源 Id 吗?

标签: android imageview


【解决方案1】:

----更新(正确答案)

您的代码中的一个问题是strPictureName 等于,例如:"myDogPicture.png"?如果是,您应该首先从字符串中删除".png"。测试一下 :) 要从具有资源 ID 的可绘制对象中获取图像,您不应该使用图像扩展。

----旧答案

您可以使用以下代码实现此目的:

// example - your ImageView
ImageView myImageView = (ImageView)findViewById(R.id.my_image_view);
// suppose the name of your image in drawable/ is my_image_name.jpg.
myImageView.setImageResource(R.drawable.my_image_name);

如果您已经知道字符串和资源 id 之间的映射关系,您对使用枚举有何看法?示例:

public enum MyImage{
        CAT_IMAGE("cat.png", R.drawable.cat),
        DOG_IMAGE("dog.png", R.drawable.dog),
        HORSE_IMAGE("horse.png", R.drawable.horse);

        private final String fileName;
        private final int resId;

        MyImage(String fileName, int resId){
            this.fileName = fileName;
            this.resId = resId;
        }

        /**
         * 
         * @param imageFileName
         * @return -1 if image not found
         */
        public int getResId(String imageFileName){
            int resId = -1;
            for (MyImage myImage : MyImage.values()) {
                if (imageFileName.equals(myImage.fileName)){
                    resId = myImage.resId;
                    break;
                }
            }
            return resId;
        }
    }

【讨论】:

  • 谢谢.. 但我需要发送到“setImageResource”的值是 R.drawable + strMyImageNameStringVariableToHoldTheActualName。 setImageResource 需要的是资源 ID,而挑战是将我的图像名称转换为 ID。
  • 谢谢,但这对于我的目的来说还不够通用。我真的期待我尝试 int intCurrImageResourceID = this.context.getResources().getIdentifier(strPictureName, "drawable", context.getPackageName());足够了。
  • 一个问题,在您的代码中,strPictureName 是否等于,例如:myDogPicture.png?如果是,您应该首先从字符串中删除“.png”。测试它:) 要从具有资源 ID 的可绘制对象中获取图像,您不应该使用图像扩展。
  • 很高兴能够帮助到您:)。我编辑了答案,以便其他人可以看到问题所在。如果您不介意,您可以将此设置为正确答案吗?干杯^^
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-02
相关资源
最近更新 更多