【问题标题】:Get image from drawable dynamically动态从drawable中获取图像
【发布时间】:2017-03-21 20:44:26
【问题描述】:

我正在开发条码阅读器应用程序,我想在读取条码时显示产品图像,所以我用产品条码编号重命名照片并将 drawables 文件夹。照片名称为ex 1234567,尝试使用barcodeNo检索。但是我在barcodeNo上遇到错误。我该怎么做?

ImageView iv = (ImageView) findViewById(R.id.imageView1);   
iv.setImageResource(R.drawable.barcodeNo);

【问题讨论】:

    标签: android imageview


    【解决方案1】:

    只需在 getImage 方法中传递您的代码,即可从可绘制文件夹中找到您的图像。

    iv.setImageResource(getImage(barcodeNo));
    
    public int getImage(String imageName) {
    
         int drawableResourceId = this.getResources().getIdentifier(imageName, "drawable", this.getPackageName());
    
         return drawableResourceId;
    }
    

    【讨论】:

    • 这有帮助吗?
    • 我在每张照片的开头添加“a”字符
    • 我可以显示你的可绘制文件夹的图像截图吗?
    • 我尝试将 a123456789 更改为 a8690504017516
    • 我用这个stackoverflow.com/questions/11737607/…解决了这个问题
    【解决方案2】:
    String uri = "@drawable/myresource";  // where myresource (without the extension) is the file
    
    int imageResource = getResources().getIdentifier(uri, null, getPackageName());
    
    imageview= (ImageView)findViewById(R.id.imageView);
    Drawable res = getResources().getDrawable(imageResource);
    imageView.setImageDrawable(res);
    OR
    imageview.setImageResource(imageResource)
    

    【讨论】:

      【解决方案3】:

      @Narendra Sorathiya 的回答是正确的。您已编写此代码来解决您在屏幕截图上发布的NullPointerException

      ImageView iv = (ImageView) findViewById(R.id.imageView1);
      iv.setImageResource(getImage(barcodeNo));
      .
      .
      .
      .
      public int getImage(String imageName) {
      
           int drawableResourceId = this.getResources().getIdentifier(imageName, "drawable", this.getPackageName());
      
           return drawableResourceId;
      }
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-17
      • 2013-06-05
      • 2014-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-22
      相关资源
      最近更新 更多