美文网首页
自定义 View——Android 中的 style 和 the

自定义 View——Android 中的 style 和 the

作者: 四喜汤圆 | 来源:发表于2019-05-12 20:11 被阅读0次

本文是对Android Styles与Themes使用攻略的学习笔记

目录

一、是什么

  • style

style 是属性集合,应用于指定 View 或 window。

  • theme

theme 是 style,应用于整个 Activity 或 Application。

二、作用

当属性多时、style 被多次复用时,可提升效率。

三、使用

1. 定义 style 文件

(1)定义位置
定义在res/values/文件夹下,文件名随意取,以xml为扩展名。style定义在和layout不同的xml文件中。

(2)定义内容

style示例

① 定义 style 的 xml 文件必须以<resources>为根节点
<resources>下的每个子元素在编译期将转化为应用资源对象,通过<style>标签中name属性的value值可以引用它们,形如@style/myStyleName

② <style>标签的name属性唯一指定

③ style 的继承

  • 作用
    复用样式。继承现有 style,然后在此基础上修改或增加属性即可。

  • 使用

继承系统 style

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

继承自定义属性,以下两种方式均可。

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

通过链接names的方式继承自定义属性

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

④ style 中可用属性
查看类参考Android官方文档

2. 将 style 应用于 UI

(1)应用于单一 View
在 xml 布局中,View 节点上增加style属性

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

style 只对直接应用的节点起作用,如果 style 用于 ViewGroup,那么该 style 只对 ViewGroup 起作用,对子 View不起作用。

(2)应用于整个 Activity 或 Application

  • 应用于整个 Activity
    AndroidManifest.xml文件中,为Activity标签增加android:theme属性,并指定为特定的style
<activity android:name=".login.LoginActivity"
            android:theme="@style/CodeFont"/>
  • 应用于整个 Application
    AndroidManifest.xml文件中,为Application标签增加android:theme属性,并指定为特定的style
<application android:theme="@style/CustomTheme"></application>

相关文章

网友评论

      本文标题:自定义 View——Android 中的 style 和 the

      本文链接:https://www.haomeiwen.com/subject/suwcaqtx.html