巧用style的另類寫法

來源:互聯網
上載者:User

看到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就可以了。當然即使不用做換膚也完全沒問題,這裡只是提供另一個思路來寫布局的屬性。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.