最近工作要实现换壁纸小功能,将代码做成demo发出来
没有采用zip格式换肤,因为只是更换一张图片背景
1.将三张图放入drawable-hdpi,我放的是480*800的
2.用sharedPreference存取皮肤的id,以便于下次启动的时候根据id来选择用哪个皮肤,在onresume()里刷新皮肤
3.存到sharedPreference的数据采用string,不能采用图片的id,因为图片的id是每次程序启动后又会重新生成的
不多说了直接上,代码
- public class ChangeSkinActivity extends Activity {
- private static final String SKIN_ID = "skin_id";
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- this.requestWindowFeature(Window.FEATURE_NO_TITLE);
- setContentView(R.layout.main);
- Button btnChangeSkin = (Button) findViewById(R.id.btnChangeSkin);
- btnChangeSkin.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- if ("bg0".equals(getSkinResourceName())) {
- setSkinResourceName("bg1");
- }else if ("bg1".equals(getSkinResourceName())) {
- setSkinResourceName("bg2");
- }else if ("bg2".equals(getSkinResourceName())) {
- setSkinResourceName("bg0");
- }
- refreshSkin();
- }
- });
- }
- @Override
- protected void onResume() {
- super.onResume();
- refreshSkin();
- }
- /**
- * 更换皮肤
- * 1.点击更换皮肤快捷菜单后
- * 2.程序运行起来后
- */
- private void refreshSkin() {
- int skinId = getSkinResourceId();
- findViewById(R.id.layout).setBackgroundResource(skinId);
- }
- private int getSkinResourceId(){
- int skinId = R.drawable.bg0;
- String skinName=getSkinResourceName();
- if(skinName.equals("bg1")){
- skinId = R.drawable.bg1;
- } else if(skinName.equals("bg2")){
- skinId = R.drawable.bg2;
- }
- return skinId;
- }
- private String getSkinResourceName() {
- try {
- SharedPreferences preferences = getSharedPreferences("skinxml", Context.MODE_PRIVATE);
- return preferences.getString(SKIN_ID, "bg0");
- } catch (Exception e) {
- e.printStackTrace();
- return "bg0";
- }
- }
- private void setSkinResourceName(String skinName) {
- SharedPreferences preferences = getSharedPreferences("skinxml", Context.MODE_PRIVATE);
- Editor editor = preferences.edit();
- editor.putString(SKIN_ID, skinName);
- editor.commit();
- }
- }
然后上效果
下载地址:http://download.csdn.net/detail/ethan_xue/4413167
http://blog.csdn.net/ethan_xue/article/details/7720177