Theme and Styles

可以用來大幅度減少XML文件中的重複內容,爲view提供統一的風格。

使用

style 和drawables的結合是衆多view保持可維護性的原理。style通過定義一系列的屬性提供給view,style也可以繼承其他的style創造複合的風格。

定義和使用style

res/values/styles/styles.xml

<style name="LargeRedFont">
    <item name ="android:textColor">#c80000</item>
    <item name ="android:textSize">40sp</item>
</style>

然後就可以在activities中使用

<TextView
  android:id="@+id/tv_text"
  style="@style/LargeRedFont"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="@string/hello_world" /> 

Inheriting Styles

許多情況下你可能想繼承一個風格然後修改某些屬性,parent 屬性可以指定一個你繼承的風格,你可以繼承其中的某些屬性然後修改其中的一項或者幾項。

<style name ="LargeBlueFont" parent="@style/LargeFont">
    <item name="android:textColor">#00007f</item>
</style>

如果你想繼承自己自定義的style,無需使用parent屬性,可以直接在name前面加上一個前綴,然後. 分隔後加上style名稱

<style name="LargeFont.Red">
    <item name="android.textColor">#C80000</item>
</style>

你可以繼續繼承自己自定義的屬性用. 分隔


<style name ="LargeFont.Red.Bold">
    <item name="android:textStyle">bold</item>
</style>

還可以繼承一個內置的的風格,但是必須使用parent 屬性

<style name="CustomButton" parent="@android:style/Widget.Button">
  <item name="android:gravity">center_vertical|center_horizontal</item>
  <item name="android:textColor">#FFFFFF</item>
</style>

使用Themes

在某些情況下我們想要在我們的application 或是activity中使用統一的主題,而不是應用在單一的view中,你可以應用一系列的style作爲一個主題添加到activity或者application中,然後每個view將會應用自身所支持的屬性。
定義一個Theme

<style name="LightThemeSelector" parent="android:Theme.AppCompat.Light">
...
</style>

其中包含item 節點,它常常是一個其他styles或者colors的引用

<style name = "LightThemeSelector" parent="android:Theme.AppCompat.Light">
    <item name="android:windowBackground">@color/custom_theme_color</itme>
    <item name ="android.colorBackground">@color/custom_theme_color</item>
</style>

自定義主題

許多情況下我們想要自定義自動的view的外觀,例如想設置textColor 在TextView或者Button中的表現,可以借用自定義主題然後指定其中view的風格獲得例如:

<style name="AppTheme" parent="AppBaseTheme">
        <!-- These are your custom properties -->
        <item name="android:buttonStyle">@style/Widget.Button.Custom</item>
        <item name="android:textViewStyle">@style/Widget.TextView.Custom</item>
    </style>

    <!-- This is the custom button styles for this application -->
    <style name="Widget.Button.Custom" parent="android:Widget.Button">
      <item name="android:textColor">#0000FF</item>
    </style>

    <!-- This is the custom textview styles for this application -->
    <style name="Widget.TextView.Custom" parent="android:Widget.TextView">
      <item name="android:textColor">#00FF00</item>
    </style>

所有的主題屬性列表
https://developer.android.com/reference/android/R.attr.html#windowBackground

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章