簡體   English   中英

使用 Android getIdentifier()

[英]Using Android getIdentifier()

我試過這個:

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' 總是以零結束。

我從一個不是 Activity 並且不擴展任何東西的輔助類內部調用這一行,所以我不能簡單地調用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()作為參數傳遞。

既然你在一個活動中,那么寫就足夠了

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 是否有一個名為ball_reddrawable

例如:

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

對於 Xamarin 用戶,我遇到了一個問題,我添加了一個帶有小寫和大寫字母的圖標(例如 iconVaccine.png ),並且指的是大寫名稱 iconVaccine。

Xamarin 將允許您執行此操作(即使您不應該這樣做),但是當應用程序被編譯時,名稱被扁平化為小寫,因此您必須按如下方式引用小寫變體:

Image Name: iconVaccine.png

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

Correct Reference: iconvaccine

希望有幫助!

雖然 Festus Tamakloe 的回答是正確的,但我發現這個函數有一個怪癖。

如果您在 xml 文件中聲明string-array ,則必須通過調用基本資源類型array來訪問它,使用string-array導致 anid 0 返回。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM