通常,在這個(gè)頁面中會(huì)用到很多控件,控件會(huì)用到很多的資源。Android系統(tǒng)本身有很多的資源,包括各種各樣的字符串、圖片、動(dòng)畫、樣式和布局等等,這些都可以在應(yīng)用程序中直接使用。這樣做的好處很多,既可以減少內(nèi)存的使用,又可以減少部分工作量,也可以縮減程序安裝包的大小。
下面從幾個(gè)方面來介紹如何利用系統(tǒng)資源。
1)利用系統(tǒng)定義的id
比如我們有一個(gè)定義ListView的xml文件,一般的,我們會(huì)寫類似下面的代碼片段。
android:id="@+id/mylist"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
2)利用系統(tǒng)的圖片資源
假設(shè)我們在應(yīng)用程序中定義了一個(gè)menu,xml文件如下。
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/menu_attachment"
android:title="附件"
android:icon="@android:drawable/ic_menu_attachment" />
</menu>
這樣做的好處,一個(gè)是美工不需要重復(fù)的做一份已有的圖片了,可以節(jié)約不少工時(shí);另一個(gè)是能保證我們的應(yīng)用程序的風(fēng)格與系統(tǒng)一致。
Android中沒有公開的資源,在xml中直接引用會(huì)報(bào)錯(cuò)。除了去找到對(duì)應(yīng)資源并拷貝到我們自己的應(yīng)用目錄下使用以外,我們還可以將引用“@android”改成“@*android”解決。比如上面引用的附件圖標(biāo),可以修改成下面的代碼。
android:icon="@*android:drawable/ic_menu_attachment"
修改后,再次Build工程,就不會(huì)報(bào)錯(cuò)了。
假設(shè)我們要實(shí)現(xiàn)一個(gè)Dialog,Dialog上面有“確定”和“取消”按鈕。就可以使用下面的代碼直接使用Android系統(tǒng)自帶的字符串。
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/yes"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:text="@android:string/yes"/>
<Button
android:id="@+id/no"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:text="@android:string/no"/>
</LinearLayout>
4)利用系統(tǒng)的Style
假設(shè)布局文件中有一個(gè)TextView,用來顯示窗口的標(biāo)題,使用中等大小字體。可以使用下面的代碼片段來定義TextView的Style。
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
5)利用系統(tǒng)的顏色定義
除了上述的各種系統(tǒng)資源以外,還可以使用系統(tǒng)定義好的顏色。在項(xiàng)目中最常用的,就是透明色的使用。代碼片段如下。
經(jīng)驗(yàn)分享:
Android系統(tǒng)本身有很多資源在應(yīng)用中都可以直接使用,具體的,可以進(jìn)入android-sdk的相應(yīng)文件夾中去查看。例如:可以進(jìn)入$android-sdk$/platforms/android-8/data/res,里面的系統(tǒng)資源就一覽無余了。
開發(fā)者需要花一些時(shí)間去熟悉這些資源,特別是圖片資源和各種Style資源,這樣在開發(fā)過程中,能夠想到有相關(guān)資源并且直接拿來使用。
新聞熱點(diǎn)
疑難解答
圖片精選