Android 用户切换APP主题

  • 准备两套 style,要求参数item标签完全相同,标签值可以更改。

    <style name="SwitchTheme1" parent="@android:style/Theme.Black">  
        <item name="colorValue">#FF00FF00</item>  
        <item name="floatValue">0.35</item>  
        <item name="integerValue">33</item>  
        <item name="booleanValue">true</item>  
        <item name="dimensionValue">76dp</item>  
        <!-- 如果string类型不是填的引用而是直接放一个字符串,在布局文件中使用正常,但代码里获取的就有问题 -->  
        <item name="stringValue">@string/hello_world</item>  
        <item name="referenceValue">@drawable/hand</item>  
    </style>  
    <style name="SwitchTheme2" parent="@android:style/Theme.Wallpaper">  
        <item name="colorValue">#FFFFFF00</item>  
        <item name="floatValue">1.44</item>  
        <item name="integerValue">55</item>  
        <item name="booleanValue">false</item>  
        <item name="dimensionValue">76px</item>  
        <item name="stringValue">@string/action_settings</item>  
        <item name="referenceValue">@drawable/ic_launcher</item>  
    </style>  
    
  • 每个需要不同的主题样式引用,修改 attr.xml 或者创建新的 resource 文件,attr 自定义属性

    <?xml version="1.0" encoding="utf-8"?>  
    <resources>  
        <attr name="colorValue" format="color" />  
        <attr name="floatValue" format="float" />  
        <attr name="integerValue" format="integer" />  
        <attr name="booleanValue" format="boolean" />  
        <attr name="dimensionValue" format="dimension" />  
        <attr name="stringValue" format="string" />  
        <attr name="referenceValue" format="reference" />  
    </resources>  
    
  • 引用时使用 ?attr/自定义属性名

    <ImageView  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:src="?attr/referenceValue" />  
    
  • 因为 setTheme 方法只在当前 Activity有效,所以如果要整体更改,需要将 setTheme 方法 放在 BaseActivity 中

    setTheme(R.style.MyAppTheme);
    setContentView(R.layout.main_activity);
    
  • 切换主题

    // 结束当前
    finish();
    // 重新打开
    Intent intent = getIntent();
    startActivity(intent);
    // 关闭界面切换动画
    overridePendingTransition(0,0);
    
  • 此时如果返回之前的界面,主题修改不会起效,建议

    singTask 模式 启动 MainActivity
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值