样式(style)和主题(theme)(二)

来源:互联网 发布:客户名单搜索软件 编辑:程序博客网 时间:2024/05/17 23:13
样式(style)和主题(theme)

二,主题资源
与样式相似,主题资源的xml文件也是放在\res\values\目录下,主题的元素<resources.../>作为跟根元素,同样使用style元素来定义主题。
主题与样式的主要区别:
1.主题不能作用于单个view组件,主题应该是对整个应用中的所有activity起作用或对指定的activity起作用。
2.主题定义的格式应该是改变窗口外观的格式,例如,窗口标题、窗口边框。

实例: 给所有窗口添加边框、背景
下面通过一个示例来介绍主题的用法。为了给所有窗口都添加边框、背最,先在
\res/values/my_style.xml文件中增加一个主题,定义煮体的<style..../>片段如下。
<?xml version="1.0" encoding="utf-8"?><resources><style name="WlhTheme">    <item name="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></resources>

上面的主题定义中使用了两个Drawable 资源,其中@drawable/star 是一张图片,@drawable/window_border是一个ShapeDrawable组资源,该资源对应的XML 文件代码如下。
<?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:bottom="7dp"       android:right="7dp"/>   <stroke android:width="10dip" android:color="#f00"/></shape>

定义了上面主题之后,接下来即可在java中使用该主题,例如如下代码
package com.example.styletest;import android.app.Activity;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;public class MainActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setTheme(R.style.WlhTheme);        setContentView(R.layout.activity_main);    }}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.styletest"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="21" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/WlhTheme" >        <activity            android:name=".MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest>


效果图:

总结:
大部分时候,在AndroidManifest.xml文件中对指定应用,指定activity应用主题更贱简单,如果我们想那个应用中全部窗口使用该主题,只要为<application.../>元素添加android:theme属性。属性值是一个主题的名字,如下代码使用:
<application android:theme="@style/WlhTheme">
....
</application>

如果只对某个activity拥有这个主题,那么可以修改<activity .../>元素,同样指定主题即可。
android:theme="@style/WlhTheme"


原创粉丝点击