您的位置:首页 > Web前端 > CSS

样式(style)和主体(theme)的回顾温习

2015-09-20 20:10 639 查看

样式(style)

Android的样式资源文件放在/res/values目录下,样式资源文件的根元素是<resources.../>元素,该元素内可包含多个<style.../>子元素,每个<style.../>元素定义一个样式。
<style.../>元素指定如下两个属性。
    name:指定样式的名称
    parent:指定该样式所继承的父样式。当继承某个父样式时,该样式会获得父样式<style.../>元素内可包含多个<item.../>子元素,每个<item../>子元素定义一个格式项。


样式的简单示例

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- 定义一个样式,指定字体的大小。字体颜色-->
    <style name="style1">
        <item name="android:textSize">20sp</item>
        <item name="android:textColor">#00d</item>
    </style>
    <!-- 定义一个样式,继承前一个样式的颜色,当然可以继承许多系统已有的样式-->
    <style name="style2" parent="@style/style1">
        <item name="android:background">#ee6</item>
        <item name="android:padding">8dp</item>
        <!-- 覆盖父样式中指定的属性-->
        <item name="android:textColor">#000</item>
    </style>
</resources>


定义过样式文件之后,接下来就可以在XML资源中按如下语法格式来使用样式了:

@[<package_name>:]style/file_name


使用的简单示例:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:orientation="vertical"
    >
    <!-- 指定使用style1的样式-->
    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="style1"
        style="@style/style1"/>
    <!-- 指定使用style2的样式-->
    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="style2"
        style="@style/style2"/>
    </LinearLayout>


效果图



主题(theme)

放置位置也是/res/values目录下,样式资源文件的根元素是
<resources.../>元素,该元素内可包含多个<style.../>子元素来定义主
题。
主题与样式的区别在于:
    主题不能作用于单个的View组件,主体应该对整个应用中的所有Activity
起作用,或者对指定的Activity起作用。
    主题定义的格式应该是改变窗口外观的格式,例如窗口标题、窗口边框等。


为了给所有窗口添加边框、背景,现在/res/values/my_style.xml中增加一个主题,定义主题的style片段如下:

<
<style name="CrazyTheme">
    <item name="andorid:windowNoTitle">true</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowFrame">@drawable/window_border</item>
    <item name="android:windowBackground">@drawable/star</item>
</style>


其中上面的window_border文件如下:

<xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle">
    <!--设置填充颜色-->
    <solid android:color="#0fff"/>
    <!--设置四周的内边距-->
    <padding android:left="7dp"
       android:top="7dp"
       android:right="7dp"
       android:bottom="7dp"/>
    <!--设置边框-->
    <stroke android:width="10dip" android:color="#f00"/>
</shape>


接下来在代码中使用是:

super.onCreate(savedInstanceState);
    setTheme(R.style.CrazyTheme);
    setContentView(R.layout.linear_layout_3);


如果我们想要整个应用中的所有窗口都是这样的效果,我们可以在AndroidManifest.xml中的application下添加如下代码:

<application android:name:theme="@style/CrazyTheme">
...

</application>


同样支持继承
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: