android 主题 定制(1)

本文介绍如何为Android应用程序实现动态主题切换功能,包括自定义属性、定义主题样式、在布局文件中引用以及在Activity中设置使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天 想对自己的app做一个主题定制,就是可以动态修改应用的主题。

分为以下几个步骤:

1,首先,要实现动态的theme,因此要自定义属于自己的attr, 在values 中新建 attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <attr name="pageBackground" fromat="style"/>
   <attr name="buttonStyle" fromat="style"/>   
   <attr name="headBackground" fromat="style"/>
   <attr name="headBackButton" fromat="style"/> 
</resources>

2,定义自己的theme,在values / style.xml 文件中加入: 

    <!-- 木质主题  -->
    <style name="theme_xylon" parent="android:Theme.Light.NoTitleBar">
        <item name="pageBackground">@style/xylon_back</item>
        <item name="headBackground">@style/xylon_head</item>
        <item name="headBackButton">@style/xylon_headback_button</item>
        <item name="buttonStyle">@style/xylon_button</item>
    </style>
    
    <style name="xylon_back">
		<item name="android:background">@drawable/xylon_bg</item>
	</style>
	<style name="xylon_button">
		<item name="android:background">@drawable/xylon_btn_selector</item>
	</style>
	<style name="xylon_head">
	    <item name="android:background">@drawable/xylon_head_bg</item>
	    <item name="android:paddingLeft">10dp</item>
	    <item name="android:paddingRight">10dp</item>
	</style>
	<style name="xylon_headback_button">
	    <item name="android:background">@drawable/xylon_btn_rect</item>
	</style>


3,布局中引用自己的 theme

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" 
    style="?pageBackground">"
等等,在需要自定义风格的地方 加上 style = "?attrName" ,这里啰嗦一句,关于 @ 和 ? 引用的区别:
@ 是之前定义了的资源,而? 是待代码动态定义的。
4,上面工作做好了后 在activity 创建之前 ,加载使用的theme,

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTheme(R.style.theme_xylon);
		setContentView(R.layout.activity_cardio_test);
}

完工。












评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值