Styles and Themes

1.概述

style是属性的集合,用来指定view或者window的外观和版式。style能够指定诸如高度,填充,字体颜色,字体大小,背景颜色等属性。style定义在与layout文件分开的xml资源文件里。

比如能够例如以下使用style:

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textColor="#00FF00"
    android:typeface="monospace"
    android:text="@string/hello" />

使用style之后:

<TextView
    style="@style/CodeFont"
    android:text="@string/hello" />
全部的style属性都被从layout xml文件里移除,然后写到一个style xml文件里,命名为:CodeFont

theme是一种style,运用在全部的activity或者application。

2.创建style

在project文件夹res/values/下,创建一个文件,名字任意,保存style属性集。xml文件的根节点必须是<resources>

样例例如以下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="CodeFont" parent="@android:style/TextAppearance.Medium">
        <item name="android:layout_width">fill_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textColor">#00FF00</item>
        <item name="android:typeface">monospace</item>
    </style>
</resources>

在编译的时候<resources>的子元素都会被转换成一个application资源对象。能够通过name来引用。parent属性可选,能够指定为还有一个style文件的id。

3.继承

<style>元素中的parent属性能够指定一个style,我们的定义的style继承于这个style。能够使用这一属性继承已有的style,而仅仅用定义或者改变部分的属性。

    <style name="GreenText" parent="@android:style/TextAppearance">
        <item name="android:textColor">#00FF00</item>
    </style>

比方上面样例,继承了TextAppearance,改动了textColor属性。

假设是使用继承自定义的style,就没有必要使用parent属性了。仅仅须要在你的新style的名字前加上已定义的style的名字。样例例如以下:

    <style name="CodeFont.Red">
        <item name="android:textColor">#FF0000</item>
    </style>

4.style的属性值

如今已经知道怎样定义一个属性文件了,以下来看看在style文件里能够定义那些属性item。查看指定view的属性的最好的方法就是查看class 參考文档。比方TextView全部可利用的属性都在TextView XML attributes列出来了。


參考文档http://developer.android.com/guide/topics/ui/themes.html#PlatformStyles


原文地址:https://www.cnblogs.com/hrhguanli/p/3788362.html