使用 Android getIdentifier()

2022-08-31 15:31:38

我试过这个:

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确实是我的软件包名称。 是它所在的文件夹,并且,文件的名称确实是 。drawableresball_red

R.java 说:

        public static final int ball_red=0x7f020027;

所以我不确定为什么它不起作用。


所以我不能使用资源,我必须传递一个上下文,我这样做:在这里:

class Collection extends SurfaceView implements SurfaceHolder.Callback {

我正在创建我的类的新实例并将其作为参数传递。getContext()


答案 1

既然你在一个活动里面,那么写就足够了

int resId = YourActivity.this.getResources().getIdentifier(
    "ball_red",
    "drawable",
    YourActivity.this.getPackageName()
);

或者,如果您不是从内部类调用它

int resourceID = getResources().getIdentifier(
    "ball_red",
    "drawable",
    getPackageName()
);

注意

getIdentifier() Returns 0 if no such resource was found. (0 is not a valid resource ID.)

检查

同时检查您的R.java是否有带有名称的drawableball_red

例如:

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()
);

答案 2

对于Xamarin用户,我遇到了一个问题,我添加了一个带有小写和大写字母的图标(例如iconVaccine.png),并且指的是大写名称iconVaccine。

Xamarin 将允许你执行此操作(即使你不应该这样做),但是当编译应用时,名称将平展为小写,因此你必须引用小写变体,如下所示:

Image Name: iconVaccine.png

Xamarin reference: iconVaccine (as created in Resource.designer.cs, but will fail)

Correct Reference: iconvaccine

希望有所帮助!


推荐