Hi,大家好,快元旦啦,提前祝大家元旦快樂,(*^__^*) 嘻嘻,今天給大家分享的是Apad Qzone換膚功能的實現,我們首先看下效果:
圖1:默認的皮膚.
圖2:點擊菜單護膚按鈕,應用更換皮膚.
通過上面的效果圖可以看出Apad Qzone的換膚功能其實是很簡單實現的,由於整個應用採取了單Activity實現方式,更換背景其實就是實現了更換主程序的Activity的背景。
這裏我們事先把幾套皮膚放在res/drawable目錄裏,然後用SharedPreferences來記錄當前皮膚的資源id.然後在程序啓動時加載Activity背景。
爲了讓大家更容易理解,我這裏簡單做了一個Demo,步驟分別如下:
第一步:新建一個Android工程命名爲SkinDemo.程序結構如下:
第二步:新建一個皮膚管理類SkinSettingManager.java,代碼如下:
- package com.tutor.skindemo;
- import android.app.Activity;
- import android.content.SharedPreferences;
- /**
- * PadQzone皮膚管理器
- * @author frankiewei
- *
- */
- public class SkinSettingManager {
- public final static String SKIN_PREF = "skinSetting";
- public SharedPreferences skinSettingPreference;
- private int[] skinResources = { R.drawable.default_wallpaper,
- R.drawable.wallpaper_c,R.drawable.wallpaper_d,R.drawable.wallpaper_f,
- R.drawable.wallpaper_g
- };
- private Activity mActivity;
- public SkinSettingManager(Activity activity) {
- this.mActivity = activity;
- skinSettingPreference = mActivity.getSharedPreferences(SKIN_PREF, 3);
- }
- /**
- * 獲取當前程序的皮膚序號
- *
- * @return
- */
- public int getSkinType() {
- String key = "skin_type";
- return skinSettingPreference.getInt(key, 0);
- }
- /**
- * 把皮膚序號寫到全局設置裏去
- *
- * @param j
- */
- public void setSkinType(int j) {
- SharedPreferences.Editor editor = skinSettingPreference.edit();
- String key = "skin_type";
- editor.putInt(key, j);
- editor.commit();
- }
- /**
- * 獲取當前皮膚的背景圖資源id
- *
- * @return
- */
- public int getCurrentSkinRes() {
- int skinLen = skinResources.length;
- int getSkinLen = getSkinType();
- if(getSkinLen >= skinLen){
- getSkinLen = 0;
- }
- return skinResources[getSkinLen];
- }
- /**
- * 用於導航欄皮膚按鈕切換皮膚
- */
- public void toggleSkins(){
- int skinType = getSkinType();
- if(skinType == skinResources.length - 1){
- skinType = 0;
- }else{
- skinType ++;
- }
- setSkinType(skinType);
- mActivity.getWindow().setBackgroundDrawable(null);
- try {
- mActivity.getWindow().setBackgroundDrawableResource(getCurrentSkinRes());
- } catch (Throwable e) {
- e.printStackTrace();
- }
- }
- /**
- * 用於初始化皮膚
- */
- public void initSkins(){
- mActivity.getWindow().setBackgroundDrawableResource(getCurrentSkinRes());
- }
- }
- package com.tutor.skindemo;
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.MotionEvent;
- public class SkinDemoActivity extends Activity {
- private SkinSettingManager mSettingManager;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- //初始化皮膚
- mSettingManager = new SkinSettingManager(this);
- mSettingManager.initSkins();
- }
- //這裏爲了簡單實現,實現換膚
- @Override
- public boolean onTouchEvent(MotionEvent event) {
- mSettingManager.toggleSkins();
- return super.onTouchEvent(event);
- }
- }
以上三步就大功告成啦!,哈哈,很容易吧,今天就講到這裏,提前祝大家元旦快樂!!!