styles and themes

来源:互联网 发布:逛数码 淘宝达人 编辑:程序博客网 时间:2024/05/16 17:12

style 是用来表征view或者window外观和格式的一种资源

如果将这种style应用到某个特定的view 那么这个view在呈现的时便能够按照我们定义的方式显示 这种style的方式 实质上是把定义在view中的内容抽离出来实现内容和设计相分离的一种方式 并且有有利于减少代码量和重复编码工作 提高复用性

style应用到activity或者application就叫做theme 本质上和应用到view上面是一样的!

theme is a style applied to an entire Activity or application, rather than an individual View 

自定义style时的parent属性类似于类继承的父类 能够将parentstyle中定义的属性在这里便是item获取到并且能够覆盖,从而实现重新定义,这也是很常见的一种做法。

如果自定义style的parent是已定义的style 只需要修改其中的某个特定的item值 则可以通过如下方式进行覆写:

  <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>

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

如上定义了两个style 第一个style 引用了android原生的style

第二个style 从名字上看似是一个新的style而实际上可以 表明了这个style的parent是CodeFont。新的style名字叫做CodeFont.Red 这中类型的style都遵循这样的name命名规则,可以理解为某种style的特殊分支stlye或者是子style 在这个stlyle中自定义了想要的parent style中的属性。

From API Guide:If you want to inherit from styles that you've defined yourself, you do not have to use the parent attribute. Instead, just prefix the name of the style you want to inherit to the name of your new style, separated by a period。

如上的style继承方式 只适用于自定义style的继承,如果使用的是android 内建的style 则必须通过parent来继承

Note: This technique for inheritance by chaining together names only works for styles defined by your own resources. You can't inherit Android built-in styles this way. To reference a built-in style, such asTextAppearance, you must use the parent attribute.

Style Properties

一个style可以指定很多属性 然后当你要覆写某些属性的时候你可能不知道这个view 对应了那些item可以覆写 这个时候最好的办法就是查找对应view的xml attribute xml文件 可以通过源码来看 但是也可以通过api 来查找相应的view 并且定位到xml attribute那个部分 就可以看到所有定义的属性及其含义了 很赞!

PS:并不是所有的R.attr的属性都可以应用到view的style中 在这些属性中以window开头的那些属性就只能够应用于theme中因为这些属性指定的都是activity或者appliation

Applying Styles and Themes to the UI

如果把一个theme应用到一个activity或者一个application中则这个activity当中的所有view都会使用者个style 如果其中的view具有style中定义的属性则这些属性将会被覆盖 如果只有一部分则覆盖一部分 如果完全没有那么这个style就对于其是透明的

如果要在代码中应用style则需要将xml中style的。换成下划线——如
   "@android:style/Theme.NoTitleBar" 转换为 R.style.Theme_NoTitleBar

0 0
原创粉丝点击