Using Android getIdentifier()

后端 未结 3 1834
萌比男神i
萌比男神i 2020-11-27 04:42

I\'ve tried this:

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

And t

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 04:57

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

提交回复
热议问题