代码之家  ›  专栏  ›  技术社区  ›  ingh.am

从字符串值设置Android图像

  •  18
  • ingh.am  · 技术社区  · 15 年前

    目前我正在我的Android应用程序中绘制PNG图像,如下所示:

    ImageView image = new ImageView(context);
    image.setImageDrawable(context.getResources().getDrawable(R.drawable.testimage))
    

    如果我在数据库中有一个图像名称列表,有没有一种方法可以使用图像名称设置上面的可绘制性?我已经有代码通过数据库了,我只是想根据从这里获取的值来绘制图像。

    例如,数据库的记录:

    ID:    Name:    ImageName:
    -      Test     testimage
    

    所以当我阅读这个记录时,我有一个值为“testimage”的字符串,然后我想将图像可绘制设置为 R.drawable.testimage .

    我想这样做的一种方式是:

    int image = R.drawable.blank; // blank image
    
    // testimage.png is the image name from the database
    if(imageName.toString().equals("testimage.png"))
        image = R.drawable.testimage;
    else if(imageName.toString().equals("another.png"))
        image = R.drawable.another;
    else if(imageName.toString().equals("etc.png"))
        image = R.drawable.etc;
    

    但是这不是很有效!

    谢谢

    4 回复  |  直到 9 年前
        1
  •  27
  •   GeekYouUp    15 年前

    有一种方法可以这样做,您可以使用resources.getIdentifier()通过字符串检索资源ID。 http://developer.android.com/reference/android/content/res/Resources.html

    类似:

    int resourceId = Activity.getResources().getIdentifier("testimage", "drawable", "your.package.name");
    
        2
  •  21
  •   Erik S    15 年前

    我正在使用:

    int resId = getResources().getIdentifier("testimage", "drawable", getPackageName());
    image.setImageResource(resId);
    

    “testimage”-对应于例如testimage.jpg,即不包括“.jpg”

    “drawable”-是资源类型,如:@drawable/testimage

    检查 Resources.getIdentifier(...)

        3
  •  0
  •   Mikpa    15 年前

    将图像放入资产/文件夹并打开

    image.setImageURI("file:///android_asset/" + nameFromDB);
    
        4
  •  -2
  •   Mudasar    9 年前

    string path=“sdcard/camera_app/name.jpg”; img.setImageDrawable(drawable.createfrompath(path));