android中控件,假如我们把样式都写死在控件的配置文件上的话。一旦改动可谓牵一发而动千军。那么我们能够把样式写在style.xml文件里。然后引用,在API14以上版本号。
该文件位于values-v14目录下。低版本号的在values目录下。
比方,我们以一个textView为例,先在style.xml文件里定义好自己的样式:
<resources>
<!--
Base application theme for API 14+. This theme completely replaces
AppBaseTheme from BOTH res/values/styles.xml and
res/values-v11/styles.xml on API 14+ devices.
-->
<style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">
<!-- API 14 theme customizations can go here. -->
</style>
<style name="text_content_style">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textColor">#ff9723</item>
<item name="android:textSize">15sp</item>
</style>
</resources>
那么我们在使用控件时,能够这样引用:
<TextView
style="@style/text_content_style"
android:text="我是style文本"
/>
有了这种做法。我们非常easy想到一种经常使用的功能:夜间模式。就是把背景和文字弄成相对黑暗一点的:
<style name="text_content_style_night">
<item name="android:background">#C5C1AA</item>
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textColor">#363636</item>
<item name="android:textSize">15sp</item>
</style>
在网页中的样式,有一个特点,就是假如写了一套CSS样式,非常多情况下都会去继承。增强代码的复用性。android的style自然也提供了这个功能。假如。我们在夜间模式中,有一个强夜间模式,就是更黑的,那么我们能够继承原来的夜间模式样式。只加深她的背景:
<style name="text_content_style_night_dark" parent="@style/text_content_style_night">
<item name="android:background">#7F7F7F</item>
</style>
至于引用样式之后。比方样式里定义了背景,控件里又又一次定义背景,那么会覆盖样式的背景。