在上一篇文章中,我們為大家詳細介紹了有關Android Menu編程方式解析的內容,來協助大家理解Android這一作業系統在介面處理上的相關操作。那麼在這篇文章中我們將會針對Android資源的相關概念為大家詳細講解有關介面布局的一些應用,加深大家對介面處理的理解。
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
這些其實是指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資源中定義,並且以可視化的方式來操作布局對應的XML檔案。可以看res/layout/main.xml這就是一個布局檔案,這裡指定了這個布局裡有哪些介面元素以及如何組織,相對位置,絕對位置等資訊。來看看其中內容:
- < ?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,包含了一個TextView,TextView的值為 MyTest.這個XML檔案被編譯後,可以使用R.layout.main的ID來從資源中取得。
於是Activity可以用setContentView(R.layout.main)來直接從Android資源取得布局,來繪製介面元素。
另一類常用的Android資源就是圖片在res/drawable/下面有一些圖片,你也可以新加一些圖片到這裡。然後就可以通過.R.drawable.xxx 的ID來從資源中取得對應的圖片。