看到style,不少人可能會說這個我知道,就是控制項寫屬性的話可以通過style來實現代碼的複用,單獨把這些屬性及其參數寫成style就可以便捷的調用。
這種寫法呢其實比較常見,如果有某些控制項用到了相同的風格,就可以用style來作,今天要講的不是這種寫法,下面先看一下案例
,這裡給的是一個reference,而且是系統的資源。官網上有寫介紹http://developer.android.com/guide/topics/resources/accessing-resources.html
<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>
這些準備工作完成後,恭喜你現在可以用 的方式來寫布局了,注意開頭是?不是@。
<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就可以了。當然即使不用做換膚也完全沒問題,這裡只是提供另一個思路來寫布局的屬性。