最近工作要实现换壁纸小功能,将代码做成demo发出来
没有采用zip格式换肤,因为只是更换一张图片背景
1.将三张图放入drawable-hdpi,我放的是480*800的
2.用sharedPreference存取皮肤的id,以便于下次启动的时候根据id来选择用哪个皮肤,在onresume()里刷新皮肤
3.存到sharedPreference的数据采用string,不能采用图片的id,因为图片的id是每次程序启动后又会重新生成的
不多说了直接上,代码publicclassChangeSkinActivityextendsActivity {
privatestaticfinalString SKIN_ID ="skin_id";
@Override
publicvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
Button btnChangeSkin = (Button) findViewById(R.id.btnChangeSkin);
btnChangeSkin.setOnClickListener(newView.OnClickListener() {
@Override
publicvoidonClick(View v) {
if("bg0".equals(getSkinResourceName())) {
setSkinResourceName("bg1");
}elseif("bg1".equals(getSkinResourceName())) {
setSkinResourceName("bg2");
}elseif("bg2".equals(getSkinResourceName())) {
setSkinResourceName("bg0");
}
refreshSkin();
}
});
}
@Override
protectedvoidonResume() {
super.onResume();
refreshSkin();
}
/**
* 更换皮肤
* 1.点击更换皮肤快捷菜单后
* 2.程序运行起来后
*/
privatevoidrefreshSkin() {
intskinId = getSkinResourceId();
findViewById(R.id.layout).setBackgroundResource(skinId);
}
privateintgetSkinResourceId(){
intskinId = R.drawable.bg0;
String skinName=getSkinResourceName();
if(skinName.equals("bg1")){
skinId = R.drawable.bg1;
}elseif(skinName.equals("bg2")){
skinId = R.drawable.bg2;
}
returnskinId;
}
privateString getSkinResourceName() {
try{
SharedPreferences preferences = getSharedPreferences("skinxml", Context.MODE_PRIVATE);
returnpreferences.getString(SKIN_ID,"bg0");
}catch(Exception e) {
e.printStackTrace();
return"bg0";
}
}
privatevoidsetSkinResourceName(String skinName) {
SharedPreferences preferences = getSharedPreferences("skinxml", Context.MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putString(SKIN_ID, skinName);
editor.commit();
}
}
然后上效果
Android工程实现换壁纸功能源码下载地址:
用户名与密码都是www.linuxidc.com
具体下载目录在 /2012年资料/9月/3日/Android工程实现换壁纸功能