我试过这个:
r = Resources.getSystem().getIdentifier("ball_red","drawable","com.Juggle2");
Log.i("FindBall","R = "+r);
这是:
r = Resources.getSystem().getIdentifier("com.Juggle2:drawable/ball_red", null, null);
但“r”总是以零结尾。
我在帮助器类中调用这一行,它不是一个活动,也不扩展任何东西,所以我不能简单地调用getResources()
,但是可以从我的SurfaceView
传递它。
最后,我想用变量替换"ball_red"
,但首先要做的是。这不管用。
com.Juggle2
确实是我的包名。drawable
是它所在的res
文件夹,文件的名称实际上是ball_red
。
R.java说:
public static final int ball_red=0x7f020027;
所以我不知道为什么不管用。
所以我不能使用参考资料,我必须传递一个上下文,我就是这样做的:在这里:
class Collection extends SurfaceView implements SurfaceHolder.Callback {
我正在创建类的一个新实例,并将其作为参数传递给getContext()
。
发布于 2013-03-18 22:39:13
既然你在一个活动中,它就足够写了
int resId = YourActivity.this.getResources().getIdentifier(
"ball_red",
"drawable",
YourActivity.this.getPackageName()
);
或者如果您不是从内部类调用它
int resourceID = getResources().getIdentifier(
"ball_red",
"drawable",
getPackageName()
);
Note
getIdentifier() Returns 0 if no such resource was found. (0 is not a valid resource ID.)
检查
还请在R.java中检查是否存在名为ball_red
的drawable
例如:
public static final class drawable {
public static final int ball_red = 0x7f020000;
}
编辑如果您不在任何活动中,则必须传递一个context instead of resources as parameter
,然后执行以下操作
int resId = context.getResources().getIdentifier(
"ball_red",
"drawable",
context.getPackageName()
);
发布于 2016-02-26 10:17:10
对于Xamarin用户,我遇到的问题是,我添加了一个带有小写字母和大写字母(例如iconVaccine.png )的图标,并引用了大写名称iconVaccine。
Xamarin将允许您这样做(尽管您不应该这么做),但是当应用程序被编译后,名称就会被简化为小写,因此您必须引用小写变体如下所示:
Image Name: iconVaccine.png
Xamarin reference: iconVaccine (as created in Resource.designer.cs, but will fail)
Correct Reference: iconvaccine
希望这能帮上忙!
发布于 2015-05-31 18:01:12
虽然的答案是正确的,但我在这个函数中发现了一个怪癖。
如果要在xml文件中声明string-array
,则必须通过调用基本资源类型array
来访问它,方法是使用string-array
结果返回anid 0。
https://stackoverflow.com/questions/15488238
复制相似问题