API Demos 2.2 研读笔记(4)——Style and Theme

styletheme的概念

 

现在借鉴官方的文档,总结一下styletheme的相关概念。

 

style是一个包含一种或者多种格式化属性的集合,可以将其作为一个单位用在layout XML的单个view上。 比如,可以定义一种style来规定文本的文字大小和颜色,然后将其应用于一个特定的view

 

theme是一个包含一种或者多种格式化属性的集合,可以将其作为一个单位用在整个application或者其中某个activity上。比如,可以定义一个theme,其中定义的文字的大小和颜色,然后将其应用于某个activity,那么这个activity中的所有文本就都是这种样式了。

 

定义style

 

1. res/values/目录下新建一个XML文件。

2. XML文件的大体格式如下,根节点是<resources>,每一个style对应一个<style>元素,style里的每一种格式化属性对应一个<item>元素。

<?xml version="1.0" encoding="utf-8"?>

<resources>

 <style name="ImageView240dpi">

  <item name="android:src">@drawable/stylogo240dpi</item>

  <item name="android:layout_width">wrap_content</item>

  <item name="android:layout_height">wrap_content</item>     

 </style> 

</resources>

3. item的值可以是fill_parent等关键字,也可以引用其它的资源类型,例如,

<?xml version="1.0" encoding="utf-8"?>

 <resources>

   <style name="CustomTheme">       

     <item name="android:windowNoTitle">true</item>

     <item name="windowFrame">@drawable/screen_frame</item>

     <item name="windowBackground">@drawable/screen_background_white</item>

     <item name="panelForegroundColor">#FF000000</item>

     <item name="panelBackgroundColor">#FFFFFFFF</item>

     <item name="panelTextColor">?panelForegroundColor</item>

     <item name="panelTextSize">14</item>

     <item name="menuItemTextColor">?panelTextColor</item>

     <item name="menuItemTextSize">?panelTextSize</item>

   </style>

 </resources>

 @符号和?符号来引用资源。@表明我们引用的资源是其它地方定义过的(也许在这个项目中或者在Android框架中)?表明我们引用的资源的值在当前加载的主题中。这通过以名字引用特定的<item>来完成(比如,panelTextColor使用了分配给panelForegroundColor的相同颜色)。这种技巧只能用在XML资源当中。

 

4. <style>中的parent属性可以使一个style继承另一个style的属性。

既可以继承Android平台上的预定义style

<style name="GreenText" parent="@android:style/TextAppearance">        

 <item name="android:textColor">#00FF00</item>    

</style>

 又可以继承自己定义的style,当继承自己定义的style时,可以不使用parent属性,只需要在name里加上被继承的stylename作为前缀即可:

<style name="GreenText.Red" parent="@android:style/TextAppearance">        

    <item name="android:textColor">#FF0000</item>    

</style>

 

使用style

 

1. style使用在view上。

<TextView style="@style/GreenText.Red" android:text="@string/hello" />

2. style应用在activity上。

  见官方custom dialog示例。

3. style应用在application上。

<application android:name="ApiDemosApplication"

 android:label="@string/activity_sample_code" 

 android:theme="@style/Theme.CustomDialog"

 android:icon="@drawable/app_sample_code">

4. Java代码中应用style

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    setTheme(android.R.style.Theme_Light);
    setContentView(R.layout.main);
}

5. 当你将一个style应用在viewgroup上时,它的内部view不会继承这些样式。 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值