Android資源應(yīng)用技巧剖析
在上一篇文章中,我們?yōu)榇蠹以敿?xì)介紹了有關(guān)Android Menu編程方式解析的內(nèi)容,來幫助大家理解Android這一操作系統(tǒng)在界面處理上的相關(guān)操作。那么在這篇文章中我們將會(huì)針對Android資源的相關(guān)概念為大家詳細(xì)講解有關(guān)界面布局的一些應(yīng)用,加深大家對界面處理的理解。
1.添加菜單menu.add(0, Menu.FIRST+1, 1, R.string.menu_open);
menu.add(0, Menu.FIRST+2, 2, R.string.menu_edit);代碼中的 R.string.menu_open/menu_edit
這些其實(shí)是指Android資源文件中的ID,映射到具體的資源,這里是映射到字符串資源menu_open, menu_edit,其具體的值可以看res/values/string.xml在這里定義了字符串的值:
- < ?xml version="1.0" encoding="utf-8"?>
- < resources>
- < string name="hello">Hello World, HelloActivity!< /string>
- < string name="app_name">HelloWorld< /string>
- < string name="menu_open">Open< /string>
- < string name="menu_edit">Edit< /string>
- < string name="menu_update">Update< /string>
- < string name="menu_close">Close< /string>
- < /resources>
在Android中,Activity顯示的布局也可在Android資源中定義,并且以可視化的方式來操作布局對應(yīng)的XML文件。可以看res/layout/main.xml這就是一個(gè)布局文件,這里指定了這個(gè)布局里有哪些界面元素以及如何組織,相對位置,絕對位置等信息。來看看其中內(nèi)容:
- < ?xml version="1.0" encoding="utf-8"?>
- < LinearLayout xmlns:android="http://
schemas.android.com/apk/res/android"- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- < TextView android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MyTest OK yest!">< /TextView>- < /LinearLayout>
這里就描述了布局為LinearLayout,包含了一個(gè)TextView,TextView的值為 MyTest.這個(gè)XML文件被編譯后,可以使用R.layout.main的ID來從資源中取得。
于是Activity可以用setContentView(R.layout.main)來直接從Android資源取得布局,來繪制界面元素。
另一類常用的Android資源就是圖片在res/drawable/下面有一些圖片,你也可以新加一些圖片到這里。然后就可以通過.R.drawable.xxx 的ID來從資源中取得對應(yīng)的圖片。
【編輯推薦】