android 主题


当你想替换整个应用的主题时,每个页面的风格都发生变化

step1:

在res/values/themes.xml文件中添加自己的主题

eg:

<!-- 红色主题 --> <style name="Theme.Red" parent="@android:style/Theme.NoTitleBar"> <item name="headerColor">#ff0000</item> <item name="bg_color">#990000</item> <item name="themeName">red</item> </style>
<!-- 绿色主题 -->
    <style name="Theme.Green" parent="@android:style/Theme.NoTitleBar">
        <item name="headerColor">#00ff00</item>
        <item name="bg_color">#009900</item>
        <item name="themeName">red</item>
    </style>


你可能发现 headerColor , bg_color 代表什么意义,他们是自己定义的属性,在res/attrs.xml文件定义的

eg:

<attr name="themeName" format="string" />
<attr name="bg_color" format="reference|color" />
<attr name="headerColor" format="reference|color" />

step2:在你的布局文件中引用这个属性,如bg_color,headerColor

eg:

<style name="bg_style">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">warp_content</item>
        <item name="android:background">?bg_color</item>
</style>
 <TextView
        android:id="@+id/title_tv"
        style="@style/bg_style"
        android:text="测试"
         />

<item name="android:background">?bg_color</item> 中?bg_color,是应用当前主题中bg_color的属性,如当前主题时Theme.Red,那么?bg_color代表的是#990000
在Eclipse 的XML编辑器上,可能会报错,说找不到bg_color,那是因为你没有选择Theme.Red 或者Theme.Green,

step3:接下来就是设置主题了,你可以再Manifest.xml文件中配置activity的主题,或者整个application的主题
eg:
 <application
        android:name=".marco.MyApp"
        android:allowBackup="false"
        android:icon="@drawable/applogo"
        android:label="@string/app_name"
        android:theme="@style/Theme.Red" >


这样,整个应用用到属性bg_color都会换成红色了,当然你会问,怎么换主题呢?

这就需要用java代码实现了

通过setTheme(R.style.Theme_Red);调用,更改主题,但是需要在setContentView()或者Layoutinflate.inflate()方法之前调用。

当然设置的主题可以配置在共享文件中,当然你也可以在MyApplication extends Application

MyApplication 里配置整个activity的主题




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值