【问题标题】:set different image by getting image's name from out side通过从外部获取图像的名称来设置不同的图像
【发布时间】:2014-07-16 14:58:28
【问题描述】:

在我的Widget 中,我有一个ImageView,我会从外面收到一个代码,这些代码在 1-40 之间,从另一侧,我的drawable 文件夹中有 40 个不同的图像,我将它们命名为与他们的相关代码相同。 现在我想做的是,通过从外部读取一个代码,在ImageView 中显示具有相同名称的图像。 例如,如果我阅读代码 33,我想在 ImageVIew 中显示名为 33 的图像。

【问题讨论】:

    标签: android android-resources


    【解决方案1】:

    对于名为“33.png”或类似名称的可绘制对象,请执行以下操作:

    int redId = getResources().getIdentifier("33", "drawable", this.getPackageName());
    
    img.setImageResource(R.drawable.my_image);
    


    而且,在一般情况下:

    void setImageByResourceName(int resourceName) { // 33 in the example above
    
        String nameStr = String.valueOf(resourceName);
    
        int redId = getResources().getIdentifier(nameStr, "drawable", this.getPackageName());
    
        img.setImageResource(R.drawable.my_image);
    
    }
    

    【讨论】:

      【解决方案2】:

      将您的图片放在资产文件夹中,您将能够按名称选择图片。 假设你的文字是 33,你的图片名称是 33.png

      AssetManager assetManager = context.getAssets();
      String fileName = "33";
      Bitmap b = BitmapFactory.decodeStream(assetManager.open(fileName + ".png"));
      imageView.setImageBitmap(b);
      

      【讨论】:

        【解决方案3】:

        您可以使用以下方法读取给定名称的 Drawable 资源:

        private static Drawable getDrawableResourceByName(Context context, String resourceName) {
            String packageName = AmbyantApplication.get().getPackageName();
            int resId = AmbyantApplication.get().getResources().getIdentifier(resourceName, "drawable", packageName);
            if (resId != 0) {
                return context.getResources().getDrawable(resId);
            } else {
                return null;
            }
        }
        

        【讨论】:

          【解决方案4】:

          如果您知道资源的名称,您可以向系统询问资源 ID。例如:

          int resId = context.getResources().getIdentifier(
              "33", "drawable", context.getPackageName());
          

          但是,此方法调用相对昂贵,因此如果必须,请尽量少用它。来自docs“注意:不鼓励使用此功能。按标识符检索资源比按名称检索资源效率更高。”

          【讨论】:

            【解决方案5】:

            您可以使用 SparseArray 或 Hashmap 将您的图像映射到整数,然后如果从服务器接收到整数,您可以根据该键设置您的可绘制对象。

            您可以通过

            在sparseArray中获取与您的键相关的图像
            SparseArray<E> t = new SparseArray<E>();
            e = t.get(key);
            .
            .
            .
            

            【讨论】:

              猜你喜欢
              • 2018-07-14
              • 1970-01-01
              • 1970-01-01
              • 2012-10-29
              • 1970-01-01
              • 1970-01-01
              • 2023-04-03
              • 2016-07-18
              • 1970-01-01
              相关资源
              最近更新 更多