看到style,不少人可能會說這個我知道,就是控件寫屬性的話可以通過style來實現代碼的復用,單獨把這些屬性及其參數寫成style就可以便捷的調用。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="CustomText" parent="@style/Text">
<item name="android:textSize">20sp</item>
<item name="android:textColor">#008</item>
</style>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<EditText
style="@style/CustomText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello, World!" />
這種寫法呢其實比較常見,如果有某些控件用到了相同的風格,就可以用style來作,今天要講的不是這種寫法,下面先看一下案例
<EditText id="text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="?android:textColorSecondary"
android:text="@string/hello_world" />
請注意其中的 android:textColor="?android:textColorSecondary" ,這里給的是一個reference,而且是系統的資源。官網上有寫介紹http://developer.android.com/guide/topics/resources/accessing-resources.html
這種寫法叫做“Referencing style attributes”即引用風格屬性,那么怎么引用自定義的東西呢,是首先需要定義attributes,這和自定義控件時寫的style聲明是一樣的,遵照下面的格式定義一個activatableItemBackground的屬性,值得類型是reference引用類型,
<resources>
<declare-styleable name="TestTheme">
<attr name="activatableItemBackground" format="reference"></attr>
</declare-styleable>
</resources>
接着定義我們的theme,並且把這個屬性用上去,theme實際上也是style,只是針對Application和Activity時的不同說法而已。
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="activatableItemBackground">@drawable/item_background</item>
</style>
</resources>
theme寫好后我們把它應用到application或者某個activity,
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.avenwu.sectionlist.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
這些准備工作完成后,恭喜你現在可以用 ?[<package_name>:][<resource_type>/]<resource_name>的方式來寫布局了,注意開頭是?不是@。
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/textView"
android:gravity="center"
android:background="?activatableItemBackground"
android:clickable="true"
android:layout_gravity="left|top"/>
這個TextView用兩個?,一個引用系統資源,background則用了我們剛剛准備的資源。
最后我們來講一下,為什么用這種方式,實際上這種寫法主要是剝離了具體的屬性值,好比我們的background,現在對應的值不是一個確定的值,它依賴於theme里面的具體賦值,這樣的話如果需要更換主題風格我們就不需要針對每個布局改來改去,只要重新寫一個對應不同資源的theme就可以了。當然即使不用做換膚也完全沒問題,這里只是提供另一個思路來寫布局的屬性。