`

Android 笔记 -- styles 和 themes

阅读更多

 
1.定义样式
  在工程的res/values目录下新加一个样式文件,文件名可以随意,但后缀是xml。 该文件的根节点是<resources>,然后每个式样有一个style节点。style结点有唯一标识名称,在style下面是item,标识了各个属性的样式值。

 <?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的节点都会在运行时,自动转变成resource对象,然后可以通过<style>的名称来引用。例如上面的样式可以这样引用:@style/CodeFont, 样式的parent属性是可选的,它可以指向一个已经定义好的style,并且在自定义的 style里的属性值会把parent的属性值覆盖掉。一个样式可以做为一个Activity的样式, 也可以做为一个Application的主题。
 
2.样式的继承
  一个样式可以继承平台原有的样式,也可以继承自定义的样式。
  继承平台原有的样式如下(一定要在parent里指定):

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

 
  继承自定义的样式如下(可以不采用parent属性):
  这种方式只要在style的name属性上加一个前缀就可以了。前缀名是自定义的那个style的名称,例如继承CodeFont的式样可以这样写:

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

 
  这种继承方式还可以不断继承下去:

<style name="CodeFont.Red.Big">
        <item name="android:textSize">30sp</item>
    </style>

 
具体一个style的item有哪些name呢?这个可以参考一个View的xml有哪些属性。所有的XML属性(XML Attributes)都可以在item中使用。对于所有可以引用的style属性,可以参考R.attr。并不是所有的View对象都会有相同的style 属性,但是如果给一个View使用了它不支持的属性后,该View只会对它支持的属性生效,其它的会被忽略。
 
3.使用Styles 和 Themes

  在View中使用

 

<TextView
    style="@style/CodeFont"
    android:text="@string/hello" />

 在application中使用

 

<application android:theme="@style/CustomTheme">

 内置的styles 和 themes 

 

<activity android:theme="@android:style/Theme.Dialog">
<activity android:theme="@android:style/Theme.Translucent">

 可以在R.style类下面找到所有的内置style和themes。使用时要把style或themes的名称下划线改为点。  比如Theme_NoTitleBar 在使用时改为"@android:style/Theme.NoTitleBar"。

在Activity中使用

 

<activity android:theme="@style/CustomDialogTheme">

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics