減少XML檔案數,減少xml
在android開發中,做出漂亮的ui的應用,往往有數量龐大的xml檔案。比如,我們要給一個Button加上一個selector,如果背景不是圖片,就得寫三個xml檔案,分別是:
edit_focused.xml
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" > <corners android:radius="3dip" /> <gradient android:angle="90" android:endColor="#ffffff" android:startColor="#000000" android:type="linear" /></shape>
edit_normal.xml
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" > <corners android:radius="5dip" /> <gradient android:angle="0" android:endColor="#000000" android:startColor="#ffffff" android:type="linear" /></shape>
selector_edit.xml
<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/edit_focus" android:state_pressed="true"></item> <item android:drawable="@drawable/edit_normal"></item></selector>
一個按鈕的selector就得三個xml,這樣算來,xml檔案的數量想少都太難了,其實我們可以把這三個檔案合并成一個,寫到一起,這樣就能很大程式上減少讓人眼花繚亂xml檔案數。如下:
selector_edit.xml
<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true"> <shape> <corners android:radius="3dip" /> <gradient android:angle="90" android:endColor="#ffffff" android:startColor="#000000" android:type="linear" /> </shape> </item> <item> <shape> <corners android:radius="5dip" /> <gradient android:angle="0" android:endColor="#000000" android:startColor="#ffffff" android:type="linear" /> </shape> </item></selector>
使用的時候和上面完全一樣。但是xml檔案的數量減少很多。
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:background="@drawable/selector_anotate_icon" android:text="@string/btn_text" />