`
bing0313
  • 浏览: 9442 次
最近访客 更多访客>>
社区版块
存档分类
最新评论

Android样式和主题(style&theme)

阅读更多
android样式:android中的样式和CSS样式作用相似,都是用于为界面定义显示风格。

在Android中定义样式,在res/values/styles.xml文件中添加以下内容
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name=“testStyle”> <!-- 为样式定义一个全局唯一的名字-->
        <item name=“android:textSize”>18px</item> <!-- name属性的值为使用了该样式的View控件的属性 -->
        <item name="android:textColor">#0000CC</item>
    </style>
</resources>

在layout文件中使用上面的android样式:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" ....>
    <TextView style="@style/testStyle"
        .....  />
</LinearLayout>

样式继承:样式也像CSS一样能继承一个父样式,继承后具有父样式的值。如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
	 <style name="textViewStyle">
	     <item name="android:textColor">#FF0000</item>
	     <item name="android:textSize">20sp</item>
	 </style>
	 
	 <!--  继承textViewStyle  -->
	 <style name="childStyle" parent="textViewStyle">
	     <item name="android:autoLink">web</item>
	     <item name="android:textColor">#00FF00</item>
	 </style>

	 <!--  继承childStyle  -->
	 <style name="childStyle.otherMethod">
	     <item name="android:textSize">15sp</item>
	 </style>
</resources>

<style>标签中有一个parent属性。其值设置为父样式即可继承,或者在name属性中前面直接加上父样式的名称 + "." + 自身样式名称
如:<style name="childStyle.otherMethod">
在R文件中会命名为childStyle_otherMethod,直接引用即可

android主题:android中主题也是用于为应用定义显示风格,它的定义和样式的定义相同,如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
	 <style name="testTheme">
             <!--  设置无标题  -->
	     <item name="android:windowNoTitle">true</item> 
             <!--  设置全屏显示 --> 
	     <item name="android:windowFullscreen">?android:windowNoTitle</item> 
	 </style>
</resources>

上面“?android:windowNoTitle”中的问号用于引用在当前主题中定义过的资源的值。即前面android:windowNoTitle的值为true的话,这里也为true

下面代码显示在AndroidManifest.xml中如何为应用设置上面定义的主题:
<application android:icon="@drawable/icon" android:label="@string/app_name"
     android:theme="@style/testTheme">
   ......
</application>

除了可以在AndroidManifest.xml中设置主题,同样也可以在代码中设置主题,如下:
setTheme(R.style.themeTest);
在定义上,样式和主题基本相同,但是它们使用的地方不同。
样式用在具体的View,如:EditText、TextView等;
主题通过AndroidManifest.xml中的<application>和<activity>用在整个应用或者某个 Activity,主题对整个应用或某个Activity进行全局性影响。如果一个应用使用了主题,同时应用下的view也使用了样式,那么当主题和样式属性发生冲突时,样式的优先级高于主题。
另外android系统也定义了一些主题,
例如:<activity android:theme=“@android:style/Theme.Dialog”>,该主题可以让Activity看起来像一个对话框,
还有透明主题:@android:style/Theme.Translucent 。如果需要查阅这些主题,可以在文档的referenceandroid-->R.style 中查看。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics