主要有以下的步驟:
- 在 attrs.xml資源文件中定義自己的屬性:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="appBg" format="reference" />
</resources>
- 在styles.xml資源文件中定義幾種主題風(fēng)格:
<resources>
<style name="theme1">
<item name="appBg">@color/login_btn_color1</item>
</style>
<style name="theme2">
<item name="appBg">@color/login_btn_color2</item>
</style>
</resources>
- 在Activity中的onCreate()函數(shù)中的setContentView()之前動態(tài)設(shè)置主題,一定要在setContentView()函數(shù)之前設(shè)置setTheme()啊:
@Override
protected void onCreate(Bundle savedInstanceState) {
mContext = this;
super.onCreate(savedInstanceState);
setTheme(getIntent().getIntExtra("theme_res", R.style.theme1));
setContentView(R.layout.activity_main);
}
//R.layout.activity_main 布局文件中需要定制主題的組件進(jìn)行如下設(shè)置(android:background:):
<Button
android:layout_width="220px"
android:layout_height="70px"
android:id="@+id/login"
android:text="登錄"
android:textColor="#FFFFFF"
android:textSize="20px"
android:gravity="center"
android:layout_marginTop="15px"
android:layout_alignParentLeft="true"
android:layout_alignParentBottom="true"
android:layout_below="@+id/layout_login"
android:background="?attr/appBg" />
- 在需要更換主題的時(shí)候,進(jìn)行重新啟動該Acticvity,并且把先前的Activity銷毀掉:
@OnClick(R.id.changeTheme1)
public void onChangeTheme1Click() {
changeTheme(R.style.theme1);
}
@OnClick(R.id.changeTheme2)
public void onChangeTheme2Click() {
changeTheme(R.style.theme2);
}
//注意要設(shè)置Intent.FLAG_ACTIVITY_CLEAR_TOP
//Intent.FLAG_ACTIVITY_NEW_TASK 這兩個(gè)標(biāo)志位
private void changeTheme(int resId) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("theme_res", resId);
startActivity(intent);
}
- 關(guān)于Style 和Theme 文章參考: