資源檔案位於專案目錄下的 res 目錄,目錄中的檔案都不能夠包含大寫字母,但檔案中的資源可以,在 XML 環境,會使用 @ 符號,代表 at 的意思,表示套用資源檔案,後面則是資源的類型和檔名。
以下示程式碼,示範在 XML 及 JAVA 語法下,如何運用資源檔案。
ID 資源
XML:
android:id="@+id/myButton" - 設定元件的 ID 為 myButton,並會自動新增至 Rosoure 中,"+" 代表新增資料到資源庫。
JAVA:
private buttonJAVA;
buttonJAVA=(Button) findViewByID(R.id.myButton); - 使用 findViewByID 方法,指定 myButton 給 ButtonJava。
圖形資源
XML:
android:background="@drawable/background" - 設定 background 套用 res\drawable 資源中 background 檔案。在 res 目錄中有多個 drawable 目錄根據解析度區分,程式會根據使用者的環境自動判斷該使用哪個目錄下的資源。
JAVA:
buttonJAVA.setBackgroundResource(R.drawable.ic_launcher); - 透過方法 setBackgroundResource 使用 Resource 內的圖形。
註:類似 set*Resource 都可以使用 Resource 內的圖形檔案 (*可以是任何單字,例如 image)。
文字資源
XML:
android:text="@string/hello" - 設定 text 套用 string.xml 中 hello 資源。 在 res 目錄中有多個 values 目錄根據地區不同區分, 程式會根據使用者的環境自動判斷該使用哪個目錄下的資源。
JAVA:
text=getString(R.string.hello); - 透過方法 getString,得到 hello 內的文字資料,如果沒用 getString 只會得到 hello 的編號資訊。
Style 資源
style="@style/myStyle" - 設定元件的 styles 套用 style.xml 中 myStyle 資源。
Layout 資源
setContentView(R.layout.main); - 透過方法 setContentView 載入layout 資源。
請先 登入 以發表留言。