android 主題 定製(1)
阿新 • • 發佈:2019-01-26
今天 想對自己的app做一個主題定製,就是可以動態修改應用的主題。
3,佈局中引用自己的 theme
@ 是之前定義了的資源,而? 是待程式碼動態定義的。
4,上面工作做好了後 在activity 建立之前 ,載入使用的theme,
分為以下幾個步驟:
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); }
完工。