【问题标题】:how to display images using filename in android如何在android中使用文件名显示图像
【发布时间】:2015-03-27 13:57:30
【问题描述】:

我正在使用 imageAdapter 类,其中我有一个存储可绘制对象的数组

public Integer[] mThumbIds = {
                  R.drawable.blue, R.drawable.floral,
                  R.drawable.bluefloral    }; 

在第一个活动中,当用户单击保存按钮时,我已将这些图像保存在 android 内部存储器中,如 data/data/com.myapp.color,我也获得了文件名和文件路径并将其传递给 imageAdapter 类 i只是想知道通过这个文件名和路径如何将这些图像保存到这个数组中。因为通过这个数组我在gridview中显示图像。

【问题讨论】:

  • 这些图片在drawable文件夹中吗?

标签: android memory internal


【解决方案1】:

这就是您如何使用它们的文件名获取图像 ID 的方法。使用此 ID,您可以在图像视图中加载图像。

如果图像名称是my_image,此方法将返回与R.id.my_image关联的id值

public static int getImageIDFromName(String imageName)
{
    int imageID = 0;
    if(imageName == null
            || imageName.equalsIgnoreCase(""))
    {
        return 0;
    }

    try
    {
        @SuppressWarnings("rawtypes")
        Class res = R.drawable.class;
        Field field = res.getField(imageName);
        imageID = field.getInt(null);
    }
    catch(Exception e)
    {

    }

    return imageID;
}

【讨论】:

    【解决方案2】:

    如果图像在内部或外部存储中,您可以通过以下方式加载它:

    Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
    ImageView imageView = (ImageView) findViewById(R.id.imageView);
    imageView.setImageBitmap(bitmap);
    

    如果图片里面的drawable文件夹在apk里面你可以使用:

    ImageView imageView = (ImageView) findViewById(R.id.imageView);
    imageView.setImageResource(R.drawable.drawable_name);
    

    如果assets文件夹内的图片可以使用:

    InputStream inputStream = getAssets().open("image_name.jpg");
    Drawable drawable = Drawable.createFromStream(inputStream, null);
    ImageView imageView = (ImageView) findViewById(R.id.imageView);
    imageView.setImageDrawable(drawable);
    

    如果 drawable 文件夹 中的图像只有名称,则可以使用以下方法获取资源 ID:

    int drawableResourceId = this.getResources().getIdentifier("image_name_without_extension", "drawable", this.getPackageName());
    

    【讨论】:

      猜你喜欢
      • 2014-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-11
      • 2017-05-27
      相关资源
      最近更新 更多