最近工作要實現換壁紙小功能,將代碼做成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();
- }
- }
然後上效果
Android工程實現換壁紙功能源碼下載地址:
免費下載地址在 http://linux.linuxidc.com/
用戶名與密碼都是www.linuxidc.com
具體下載目錄在 /2012年資料/9月/3日/Android工程實現換壁紙功能