Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

java - Using Android getIdentifier()

I've tried this:

r = Resources.getSystem().getIdentifier("ball_red","drawable","com.Juggle2");
Log.i("FindBall","R = "+r);

And this:

r = Resources.getSystem().getIdentifier("com.Juggle2:drawable/ball_red", null, null);

But 'r' always ends up as zero.

I'm calling this line from inside a helper class that's not an Activity and doesn't extend anything, so I can't simply call getResources(), but I can pass it from my SurfaceView.

Eventually, I want to replace "ball_red" with a variable, but first thing's first. This isn't working.

com.Juggle2 is indeed my package name. drawable is the res folder that it's in, and, the name of the file is indeed ball_red.

R.java says:

        public static final int ball_red=0x7f020027;

So I'm not sure why it isn't working.


So I can't use Resources, I must pass a context, and I'm doing that this way: Inside here:

class Collection extends SurfaceView implements SurfaceHolder.Callback {

I'm making a new instance of my class and passing it getContext() as a parameter.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since you are inside of an activity it is enough to write

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

or if you're not calling it from an inner class

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.)

Check

Check also in your R.java whether there is a drawable with the name ball_red

e.g.:

public static final class drawable {
        public static final int ball_red = 0x7f020000;
 }

EDIT If you're not in any activity then you must pass a context instead of resources as parameter then do this

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...