安卓应用换肤
package com.example.changeskin;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
private int mThemeId = -1; // 皮肤主题ID,默认-1 不处理
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
if (savedInstanceState.getInt("theme", -1) != -1) {// 读取皮肤主题ID,-1 不处理
mThemeId = savedInstanceState.getInt("theme");
this.setTheme(mThemeId); //设置主题皮肤
}
}
setContentView(R.layout.activity_main);
this.findViewById(R.id.changeSkin1).setOnClickListener(mOnClickListener); // day 明亮主题
this.findViewById(R.id.changeSkin2).setOnClickListener(mOnClickListener); //night 黑暗主题
}
View.OnClickListener mOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.changeSkin1:
onTheme(R.style.theme1);
break;
case R.id.changeSkin2:
onTheme(R.style.theme2);
break;
default:
}
}
};
// 设置主题,并重建
private void onTheme(int iThemeId){
mThemeId = iThemeId;
this.recreate();
}
// 保存主题ID,onCreate 时读取主题
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("theme", mThemeId);
}
}