简体   繁体   English

如何获取在可绘制文件夹中分配的图像的名称?

[英]How to get the name of the image which is allocated in drawable folder?

In my Android application, in SQLite db, I have a picture attribute of type String. 在我的Android应用程序的SQLite db中,我具有一个String类型的picture属性。

The following code works and allows me to retrieve image from drawable folder and display it in the ImageView. 以下代码有效,并允许我从可绘制文件夹中检索图像并将其显示在ImageView中。

protected ImageView pictureView;
...
pictureView = (ImageView) findViewById(R.id.pictureView);
pictureView.setImageDrawable(getResources().getDrawable(R.drawable.howard));
// howard.png is my image

The problem is that I can't get the images of my objects dynamically because my code for generating string that represents the name of the image in drawable doesn't seem to work. 问题是我无法动态获取对象的图像,因为用于生成表示可绘制图像中图像名称的字符串的代码似乎无法正常工作。

I tried to do it these ways but it doesn't work. 我尝试通过这些方式进行操作,但无法正常工作。

1st way: 第一种方式:

Resources res = getResources();
String picture = cursor.getString(cursor.getColumnIndex("picture"));
int id = getResources().getIdentifier("samples.companydirectory.drawable/" + picture, null, null);
Drawable drawable = res.getDrawable(id);
pictureView.setImageDrawable(drawable);

2nd way: 第二种方式:

pictureView = (ImageView) findViewById(R.id.pictureView);
String picture = cursor.getString(cursor.getColumnIndex("picture"));
int id = getResources().getIdentifier("samples.companydirectory.drawable/" + picture, null, null);
pictureView.setImageResource(id);

XML code: XML代码:

<ImageView
            android:id="@+id/pictureView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

What am I doing wrong? 我究竟做错了什么?

I have a class like so many things 我有很多东西

public static int getResourceId(Context context, String name)
   {
       int resourceId = context.getResources().getIdentifier(name, "drawable", context.getPackageName());       
       return resourceId;
   }

In your case is well 你的情况很好

pictureView = (ImageView) findViewById(R.id.pictureView);
String picture = cursor.getString(cursor.getColumnIndex("picture"));
int id = getResources().getIdentifier(picture, "drawable", context.getPackageName());
pictureView.setImageResource(id);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM