2010-09-06 110 views
29

我該如何做到這一點:動態資源加載Android

我想找到一種方法來打開名稱是在運行時只確定的資源。

讓我解釋更多的細節

我想有一個XML引用一堆其他的XML文件中的應用APK。

出於說明的目的,假設主XML是main.xml,其他XML是file1.xml file2.xml,fileX.xml。

我想要的是讀取main.xml,提取我想要的XML名稱(fileX.xml)。然後讀取fileX.XML。

我所面臨的問題是什麼,我解壓形式的main.xml是一個字符串,我無法找到一個方法來改變,要R.raw.nameOfTheFile

任何人有一個想法?

我不想:

  • 重組一切都在一個巨大的XML文件中,一些/串鏈接到資源ID
一個巨大的開關情況
  • 硬編碼的main.xml
  • +0

    我面臨類似的問題,但我沒有得到任何接受的答案。任何人都可以爲這個問題開始賞金嗎? – 2013-08-30 08:48:22

    回答

    51

    我還沒有原始文件或XML佈局文件中使用它,但可繪我用這個:

    getResources().getIdentifier("fileX", "drawable","com.yourapppackage.www"); 
    

    獲取資源的標識符(R.id)。您需要用其他東西替換drawable,可能是rawlayout(未經測試)。

    +0

    非常感謝您的答案。對於那些在同一個案例[這裏是關於這個問題的一個很好的解釋](http://www.anddev.org/tinytut_-_get_resources_by_name__getidentifier_-t460.html)(一旦我有了這個函數的名字,它很簡單):' getResources()。getIdentifier(「fileX」,「raw」,應用程序包);' – 2010-09-06 05:22:06

    +1

    Dead link? @JasonRogers啊,nvm - 它應該是http://www.anddev.org/tinytut_-get_resources_by_name__getidentifier-t460.html – aaronsnoswell 2012-07-20 02:31:12

    +1

    不是沒有死鏈接casperOne刪除我的帖子,並將其更改爲一條評論,沒有花時間做正確的(又名斷鏈接)這裏是鏈接:http://www.anddev.org/tinytut_-_get_resources_by_name__getidentifier_-t460.html – 2012-07-20 10:53:34

    23

    我寫了這方便的小助手方法來封裝此:

    public static String getResourceString(String name, Context context) { 
        int nameResourceID = context.getResources().getIdentifier(name, "string", context.getApplicationInfo().packageName); 
        if (nameResourceID == 0) { 
         throw new IllegalArgumentException("No resource string found with name " + name); 
        } else { 
         return context.getString(nameResourceID); 
        } 
    } 
    
    +0

    非常有用,謝謝,但我們永遠不會想要一個字符串。有時候一條小溪會更好。 – 2011-12-23 00:31:13

    6

    還有另一種方法:

    int drawableId = R.drawable.class.getField("file1").getInt(null); 
    

    根據this blog它比使用則getIdentifier快5倍倍。