Android开发经验谈Android开发Android开发

Android样式开发之style、theme、attr总结

2017-11-01  本文已影响190人  芒果味的你呀

大纲:

  • Attr:属性,风格样式的最小单元;
  • Style:风格,它是一系列Attr的集合用以定义一个View的样式,比如height、width、padding等;
  • Theme:主题,它与Style作用一样,不同于Style作用于个一个单独View,而它是作用于Activity上或是整个应用。

attr

看一看源码中的代码片段

<declare-styleable name="ViewGroup_Layout">
    <attr name="layout_width" format="dimension">
        <enum name="fill_parent" value="-1" />
        <enum name="match_parent" value="-1" />
        <enum name="wrap_content" value="-2" />
    </attr>
    ...
</declare-styleable>

如果我们自己想使用可以在values下新建一个attrs.xml,在<resources>元素里面首先申明一个自己的<declare-styleable>表示一个属性组,再在里面加上属性就行。


Style

样式style是指为view或窗口指定外观和格式的属性集合。样式可以指定高度、填充、字体颜色、字号、背景色等许多属性。 样式是在与指定布局的 XML 不同的 XML 资源中进行定义。

定义样式:

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

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

Theme:是指对整个Activity或应用application而不是对单个 view应用的样式。 以主题形式应用样式时,Activity 或应用中的每个视图都将应用其支持的每个样式属性。 例如,您可以 Activity 主题形式应用同一 CodeFont样式,之后该 Activity 内的所有文本都将具有该字体的样式。需要在相应的<activity>标签或<application>标签里设置android:theme属性,引用的其实也是style,但一般称为主题。

<resources> 
    <style name="AppTheme" parent="Theme.AppCompat">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
        <item name="windowAnimationStyle">@style/WindowAnimation</item>
    </style>
</resources>

使用:
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">
    <!-- activity here -->
</application>

应用

设置样式的方法有两种:

上一篇 下一篇

猜你喜欢

热点阅读