可以用来大幅度减少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