图像到整数

时间:2011-11-16 11:19:40

标签: android

如何将图像资源转换为整数? 我用过这个:

int rh=this.getResources().getIdentifier("ic_launcher", null, this.getPackageName());

但它无法正常工作。 我logcat这个,rh的值总是0。 有没有其他方法可以将图像转换为整数?

5 个答案:

答案 0 :(得分:2)

你的这个:

int i = this.getResources().getIdentifier("ic_launcher", "strings", this.getPackageName());

int i = this.getResources().getIdentifier("ic_launcher", "drawable", this.getPackageName());

其中1个应该正常工作。

答案 1 :(得分:2)

尝试使用此指定类型:

int rh=this.getResources().getIdentifier("ic_launcher", "drawable", this.getPackageName());

请记住,它不是将图像转换为整数,getIdentifier()只是找到用于查找.apk文件中打包资源的资源ID。

答案 2 :(得分:1)

您也可以在不使用资源的情况下实现此目的。

int id=R.drawable.icon;

此处,icon是您的可绘制文件夹中的图片。

将此id值设置为整数

ImageView imageView=null;
imageView.setImageResource(id);

答案 3 :(得分:0)

试试这个,

int id = getResources().getIdentifier("ic_launcher","drawable", getPackageName());

并返回资源ID,即整数。

答案 4 :(得分:0)

如果其他方法都不起作用,请尝试以下代码:

public static int getResId(String variableName, Class<?> c) {
Field field = null;
int resId = 0;
try {
    field = c.getField(variableName);
    try {
        resId = field.getInt(null);
    } catch (Exception e) {
        e.printStackTrace();
    }
} catch (Exception e) {
    e.printStackTrace();
}
return resId;

}

你的情况:

int x = getResId("ic_launcher", R.drawable-???.class);

在哪里???是正确的drawable文件夹。