Android 中的 theme 和 style(1)
從技術層面上theme 和style 沒有什麼區別
要說到兩者的不同就是我們在 Android 應用使用Theme 和Style 的方法是不同的。
<style name="myStyle"> <item name="android:background"> @color/colorAccent </item> </style>
屬性(Attribute)
屬性就是鍵值對的鍵,通常也會在其中宣告值的格式和型別。定義了值的型別可以便於儲存值,同時也便於根據值的型別讀取值。
屬性值的型別
-
資源型別
1fraction
屬性定義
<attr name = "pivotX" format = "fraction" />
屬性使用
<rotate android:pivotX = "200%"/>
2float
屬性定義
<attr name = "fromAlpha" format = "float" />
屬性使用
<alpha android:fromAlpha = "1.0"/>
3boolean
屬性定義
<attr name = "focusable" format = "boolean" />
屬性使用
<Button android:focusable = "true"/>
4color
屬性定義
<attr name = "textColor" format = "color" />
屬性使用
<TextView android:textColor = "#00FF00" />
5string
屬性定義
<attr name = "text" format = "string" />
屬性使用
<TextView android:text = "我是文字"/>
6dimension
屬性定義
<attr name = "layout_width" format = "dimension" />
屬性使用
<Button android:layout_width = "42dip"/>
7integer
屬性定義
<attr name = "framesCount" format="integer" />
屬性使用
<animated-rotate android:framesCount = "12"/>
-
特殊型別
這裡之所以叫特殊型別 是因為他們只會被在定義屬性時使用。
8flag
屬性定義
<declare-styleable name="名稱"> <attr name="gravity"> <flag name="top" value="0x30" /> <flag name="bottom" value="0x50" /> <flag name="left" value="0x03" /> <flag name="right" value="0x05" /> <flag name="center_vertical" value="0x10" /> ... </attr> </declare-styleable>
屬性使用
<TextView android:gravity="bottom|left"/>
9enum
屬性定義
<declare-styleable name="名稱"> <attr name="orientation"> <enum name="horizontal" value="0" /> <enum name="vertical" value="1" /> </attr> </declare-styleable>
屬性使用
<LinearLayout android:orientation = "vertical"> </LinearLayout>
10reference
屬性定義
<declare-styleable name = "名稱"> <attr name = "background" format = "reference" /> </declare-styleable>
屬性使用
<ImageView android:background = "@drawable/圖片ID"/>
屬性的名稱空間
android 框架提供 android schema 來給出該 xml 解析的規範,當然也可以自己定義 schema 來解釋 xml 中 tag 和屬性以及值的意義。
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
自定義屬性
當然也可以自己定義屬性,其實現在使用 android 庫就存在一些自定義屬性,值得注意的是我們自己定義的屬性在應用級別是全域性的,如果兩個屬性名稱相同勢必造成在構建(build)專案發生衝突錯誤。
- 名稱空間的是全域性的
- 所有的屬性都遵守應用的 schema
theme 和 style 的區別
主題
void setTheme(int themeResId); Theme getTheme();
可以在 Activity 中呼叫 setTheme() 然後傳入 theme 資源id,就會在預設 theme 上新增自己配置或定義的 theme。同樣可以通過 getTheme 獲取當前的 theme。
其實主題自己本身並沒有做什麼,僅僅是用於儲存一個配置。
應用預設元件樣式
android:editTextStyle
例如我們在佈局引入 editText 我們就會應用一個 editTextStyle 預設的元件樣式,元件預設的樣式就是在主題(theme)中定義的。每一個元件都自己的不同的預設樣式名稱。例如 editText 的預設樣式是 editTextStyle, textview 的預設樣式是 textviewStyle。
顏色值
android:textColorPrimary
我們還有一些顏色值,通常大多數顏色值都是用於定義文字顏色。例如 textColorPrimary、textColorSecondary 和 teriary 等等。
文字外觀樣式
android:textAppearanceSmall
視窗配置值
android:windowActionBar
當您的 activity 或 dialog 建立時候, 在內部的已經 建立 window,根據配置是否有 actionBar,如果有 actionBar 會載入 actionBar 檢視。