style和自定义style

style是什么?

A style is a collection of properties that specify the look and format for a View or window.

style是定义了决定view或者窗口外观与格式的一组属性的集合~可以想象成一个游戏里的npc角色,当需要创建很多次时(小怪),可以把相同的属性都打包放在一起(血量、攻击力等),创建时直接加上即可,就不需要重复定义这些属性(听起来有点像java里面的superclass==)

style定义的xml放在哪里?

The name of the XML file is arbitrary, but it must use the .xml extension and be saved in the res/values/ folder.

名字随意,必须.xml后缀,放在res/values/目录下。

style和theme针对谁?

A theme is a style applied to an entire Activity or application, rather than an individual View
A style such as the one defined above can be applied as a style for a single View or as a theme for an entire Activity or application.

theme针对单独的activity或者整个app,style针对单个的view不过theme也可以使用style。

如何自定义style?

直接盗代码

<?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必须是根节点
  • name必须有,使用的时候就是引用name
  • item元素的name必须有,其对于view子类的所有属性;如果某个引用了某个style的view中不支持or不存在该style中定义的属性,该属性会被忽略
  • parent属性表示继承了某个style或者theme;如果继承的也是同一个应用里定义的属性,就不需要加parent属性直接加"."引用即可。如
    <style name="CodeFont.Red">
        <item name="android:textColor">#FF0000</item>
    </style>

就表明该style继承了CodeFont;这种引用可以传递:

    <style name="CodeFont.Red.Big">
        <item name="android:textSize">30sp</item>
    </style>
  • 三种场景的使用:单个view在布局文件中,activity或application在清单文件中。
<TextView
    style="@style/CodeFont"
    android:text="@string/hello" />
<application android:theme="@style/CustomTheme">
<activity android:theme="@android:style/Theme.Translucent">

如何让自己的应用适配不同的api level?

在res/目录下定义一个副本文件夹,并写一个style的副本(name相同)就可以,比如
res/values-v11

系统的theme在哪里?

放链接,能看到详细的属性:
Android Styles (styles.xml)
Android Themes (themes.xml)

原文地址:https://www.cnblogs.com/Russel/p/6017258.html