Android動(dòng)態(tài)換膚原理解析及實(shí)踐

前言:

本文主要講述如何在項(xiàng)目中,在不重啟應(yīng)用的情況下,實(shí)現(xiàn)動(dòng)態(tài)換膚的效果。換膚這塊做的比較好的,有網(wǎng)易云音樂,qq等,給用戶帶來了多樣的界面選擇和個(gè)性化定制。之前看到換膚的效果后對(duì)這塊也比較好奇,就抽時(shí)間研究了下,今天給大家分享解析原理和實(shí)踐中遇到的問題。

為什么要做動(dòng)態(tài)換膚:

  • 動(dòng)態(tài)換膚可以滿足日常產(chǎn)品和運(yùn)營(yíng)需求,滿足用戶個(gè)性化界面定制的需求等等。
  • 動(dòng)態(tài)換膚,相比于靜態(tài)皮膚,可以減小apk大小
  • 皮膚模塊獨(dú)立便于維護(hù)
  • 由服務(wù)器下發(fā),不需要發(fā)版即可實(shí)現(xiàn)動(dòng)態(tài)更新

換膚的一般實(shí)現(xiàn)思路:

  • 資源打包靜態(tài)替換方案:
    指定資源路徑地址,在打包時(shí)將對(duì)應(yīng)資源打包進(jìn)去
    build.gradle中進(jìn)行對(duì)應(yīng)配置

    sourceSets {
    // 測(cè)試版本和線上版本用同一套資源
      YymTest {
          res.srcDirs = ["src/Yym/res", "src/YymTest/res"]
          assets.srcDirs = ["src/Yym/assets"]
       }
     }
    

    這種方式是在打包時(shí),通過指定資源文件的路徑在編譯打包時(shí)將對(duì)應(yīng)的資源打包進(jìn)去,以實(shí)現(xiàn)不同的主題樣式等換膚需求。適合發(fā)布馬甲版本的app需求。

  • 動(dòng)態(tài)換膚方案:
    應(yīng)用運(yùn)行時(shí),選擇皮膚后,在主app中拿到對(duì)應(yīng)皮膚包的Resource,將皮膚包中的
    資源動(dòng)態(tài)加載到應(yīng)用中展示并呈現(xiàn)給用戶。

動(dòng)態(tài)換膚的一般步驟為:

  1. 下載并加載皮膚包
  2. 拿到皮膚包Resource對(duì)象
  3. 標(biāo)記需要換膚的View
  4. 切換時(shí)即時(shí)刷新頁面
  5. 制作皮膚包
  6. 換膚整體框架的搭建

如何拿到皮膚包Resouce對(duì)象:

PackageManager mPm = context.getPackageManager();
                    PackageInfo mInfo = mPm.getPackageArchiveInfo(skinPkgPath, 
PackageManager.GET_ACTIVITIES);
skinPackageName = mInfo.packageName;

AssetManager assetManager = AssetManager.class.newInstance();
Method addAssetPath = assetManager.getClass().getMethod("addAssetPath", String.class);
addAssetPath.invoke(assetManager, skinPkgPath);

Resources superRes = context.getResources();
Resources skinResource = new 
Resources(assetManager,superRes.getDisplayMetrics(),superRes.getConfiguration());

其中需要傳入的參數(shù)即為皮膚包的文件路徑地址,還有當(dāng)前app的context
其中superResource為當(dāng)前app的Resource對(duì)象,而skinResource即為加載后的皮膚包的Resource對(duì)象。
皮膚包的資源即可通過skinResource.getIdentifier(resName, "color", skinPackageName);這種方式拿到了。

如何標(biāo)記需要換膚的View

  • 如何找到需要換膚的View

    1)通過xml標(biāo)記的View:
    這種方式主要要通過實(shí)現(xiàn)LayoutInflate.Factory2這個(gè)接口(為支持AppcompotActivty 用LayoutInflaterFactory API是一樣的)。

/**
* Used with {@code LayoutInflaterCompat.setFactory()}. Offers the same API as
* {@code LayoutInflater.Factory2}.
*/
public interface LayoutInflaterFactory {

/**
 * Hook you can supply that is called when inflating from a LayoutInflater.
 * You can use this to customize the tag names available in your XML
 * layout files.
 *
 * @param parent The parent that the created view will be placed
 * in; <em>note that this may be null</em>.
 * @param name Tag name to be inflated.
 * @param context The context the view is being created in.
 * @param attrs Inflation attributes as specified in XML file.
 *
 * @return View Newly created view. Return null for the default
 *         behavior.
 */
public View onCreateView(View parent, String name, Context context, AttributeSet attrs);
}

LayoutInflater 提供了setFactory(LayoutInflater.Factory factory)和setFactory2(LayoutInflater.Factory2 factory)兩個(gè)方法可以讓你去自定義布局的填充(有點(diǎn)類似于過濾器,我們?cè)谔畛溥@個(gè)View之前可以做一些額外的事),F(xiàn)actory2 是在API 11才添加的。
通過實(shí)現(xiàn)這兩個(gè)接口可以實(shí)現(xiàn)View的重寫。Activity本身就默認(rèn)實(shí)現(xiàn)了Factory接口,所以我們復(fù)寫了Factory的onCreateView之后,就可以不通過系統(tǒng)層而是自己截獲從xml映射的View進(jìn)行相關(guān)View創(chuàng)建的操作,包括對(duì)View的屬性進(jìn)行設(shè)置(比如背景色,字體大小,顏色等)以實(shí)現(xiàn)換膚的效果。如果onCreateView返回null的話,會(huì)將創(chuàng)建View的操作交給Activity默認(rèn)實(shí)現(xiàn)的Factory的onCreateView處理。

SkinInflaterFactory:

public class SkinInflaterFactory implements LayoutInflaterFactory {

private static final boolean DEBUG = true;

/**
 * Store the view item that need skin changing in the activity
 */
private List<SkinItem> mSkinItems = new ArrayList<SkinItem>();
@Override
public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
    // if this is NOT enable to be skined , simplly skip it
    boolean isSkinEnable = attrs.getAttributeBooleanValue(SkinConfig.NAMESPACE, SkinConfig.ATTR_SKIN_ENABLE, false);
    Log.d("ansen", "isSkinEnable----->" + isSkinEnable);
    Log.d("ansen", "name----->" + name);
    if (!isSkinEnable) {
        return null;
    }

    View view = createView(context, name, attrs);

    if (view == null) {
        return null;
    }

    parseSkinAttr(context, attrs, view);

    return view;
}


/**
 * Invoke low-level function for instantiating a view by name. This attempts to
 * instantiate a view class of the given <var>name</var> found in this
 * LayoutInflater's ClassLoader.
 *
 * @param context
 * @param name    The full name of the class to be instantiated.
 * @param attrs   The XML attributes supplied for this instance.
 * @return View The newly instantiated view, or null.
 */
private View createView(Context context, String name, AttributeSet attrs) {
    View view = null;
    try {
        if (-1 == name.indexOf('.')) {
            view = createViewFromPrefix(context, name, "android.view.", attrs);
            if (view == null) {
                view=createViewFromPrefix(context, name, "android.widget.", attrs);
                if(view==null){
                    view= createViewFromPrefix(context, name, "android.webkit.", attrs);
                }
            }

        } else {
            L.i("自定義View to create " + name);
            view=createViewFromPrefix(context, name, null, attrs);
        }

    } catch (Exception e) {
        L.e("error while create 【" + name + "】 : " + e.getMessage());
        view = null;
    }
    return view;
}

private View createViewFromPrefix(Context context, String name, String prefix, AttributeSet attrs) {
    View view;
    try {
        view = createView(context, name, prefix, attrs);
    } catch (Exception e) {
        view = null;
    }
    return view;

}

public void applySkin() {
    if (ListUtils.isEmpty(mSkinItems)) {
        return;
    }

    for (SkinItem si : mSkinItems) {
        if (si.view == null) {
            continue;
        }
        si.apply();
    }
  }

public void addSkinView(SkinItem item) {
    mSkinItems.add(item);
 }

}

對(duì)View屬性進(jìn)行識(shí)別并轉(zhuǎn)化為皮膚屬性實(shí)體

  /**
     * Collect skin able tag such as background , textColor and so on
     *
     * @param context
     * @param attrs
     * @param view
     */
    private void parseSkinAttr(Context context, AttributeSet attrs, View view) {
        List<SkinAttr> viewAttrs = new ArrayList<SkinAttr>();

        for (int i = 0; i < attrs.getAttributeCount(); i++) {
        String attrName = attrs.getAttributeName(i);
        String attrValue = attrs.getAttributeValue(i);

        if (!AttrFactory.isSupportedAttr(attrName)) {
            continue;
        }

        if (attrValue.startsWith("@")) {
            try {
                int id = Integer.parseInt(attrValue.substring(1));
                String entryName = context.getResources().getResourceEntryName(id);
                String typeName = context.getResources().getResourceTypeName(id);
                SkinAttr mSkinAttr = AttrFactory.get(attrName, id, entryName, typeName);
                if (mSkinAttr != null) {
                    viewAttrs.add(mSkinAttr);
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
            } catch (NotFoundException e) {
                e.printStackTrace();
            }
          }
        }

        if (!ListUtils.isEmpty(viewAttrs)) {
        SkinItem skinItem = new SkinItem();
        skinItem.view = view;
        skinItem.attrs = viewAttrs;

        mSkinItems.add(skinItem);

        if (SkinManager.getInstance().isExternalSkin()) {
            skinItem.apply();
            }
        }

下面通過skin:enbale="true"這種方式,對(duì)布局中需要換膚的View進(jìn)行標(biāo)記

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:skin="http://schemas.android.com/android/skin"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical"
  android:background="@color/hall_back_color"
  skin:enable="true"
  >

<code.solution.widget.CustomActivityBar
    android:id="@+id/custom_activity_bar"
    android:layout_width="match_parent"
    android:layout_height="@dimen/widget_action_bar_height"
    app:common_activity_title="@string/app_name"
    app:common_activity_title_gravity="center"
    app:common_activity_title_icon="@drawable/ic_win_cp"
    />
</LinearLayout>

在SKinInflaterFactory的onCreateView 方法中,實(shí)際是對(duì)xml中映射的每個(gè)View
進(jìn)行過濾。如果skin:enbale不為true則直接返回null交給系統(tǒng)默認(rèn)去創(chuàng)建。而如果為true,則自己去創(chuàng)建這個(gè)View,并將這個(gè)VIew的所有屬性比如id, width height,textColor,background等與支持換膚的屬性進(jìn)行對(duì)比。比如我們支持換background textColor listSelector等, android:background="@color/hall_back_color" 這個(gè)屬性,在進(jìn)行換膚的時(shí)候,如果皮膚包里存在hall_back_color這個(gè)值的設(shè)置,就將這個(gè)顏色值替換為皮膚包里的顏色值,以完成換膚的需求。同時(shí),也會(huì)將這個(gè)需要換膚的View保存起來。

如果在切換換膚之后,進(jìn)入一個(gè)新的頁面,就在進(jìn)入這個(gè)頁面Activity的 InlfaterFacory的onCreateView里根據(jù)skin:enable="true" 這個(gè)標(biāo)記,進(jìn)行判斷。為true則進(jìn)行換膚操作。而對(duì)于切換換膚操作時(shí),已經(jīng)存在的頁面,就對(duì)這幾個(gè)存在頁面保存好的需要換膚的View進(jìn)行換膚操作。

2)在代碼中動(dòng)態(tài)添加的View

上述是針對(duì)在布局中設(shè)置skin:ebable="true"的View進(jìn)行換膚,那么如果我們的View不是通過布局文件,而是通過在代碼種創(chuàng)建的View,怎樣換膚呢?

public void dynamicAddSkinEnableView(Context context, View view, List<DynamicAttr> pDAttrs) {
    List<SkinAttr> viewAttrs = new ArrayList<SkinAttr>();
    SkinItem skinItem = new SkinItem();
    skinItem.view = view;

    for (DynamicAttr dAttr : pDAttrs) {
        int id = dAttr.refResId;
        String entryName = context.getResources().getResourceEntryName(id);
        String typeName = context.getResources().getResourceTypeName(id);
        SkinAttr mSkinAttr = AttrFactory.get(dAttr.attrName, id, entryName, typeName);
        viewAttrs.add(mSkinAttr);
    }

    skinItem.attrs = viewAttrs;
    skinItem.apply();
    addSkinView(skinItem);
}

public void dynamicAddSkinEnableView(Context context, View view, String attrName, int attrValueResId)     {
    int id = attrValueResId;
    String entryName = context.getResources().getResourceEntryName(id);
    String typeName = context.getResources().getResourceTypeName(id);
    SkinAttr mSkinAttr = AttrFactory.get(attrName, id, entryName, typeName);
    SkinItem skinItem = new SkinItem();
    skinItem.view = view;
    List<SkinAttr> viewAttrs = new ArrayList<SkinAttr>();
    viewAttrs.add(mSkinAttr);
    skinItem.attrs = viewAttrs;
    skinItem.apply();
    addSkinView(skinItem);
}

即在Activity中通過比如
dynamicAddSkinEnableView(context, mTextView,"textColor",R.color.main_text_color)即可完成對(duì)動(dòng)態(tài)創(chuàng)建的View的換膚操作。

本文研究是基于github開源項(xiàng)目Android-Skin-Loader進(jìn)行的。這個(gè)框架主要是動(dòng)態(tài)加載皮膚包,在不需要重啟應(yīng)用的前提下,實(shí)現(xiàn)對(duì)頁面布局等動(dòng)態(tài)換膚的操作。皮膚包獨(dú)立制作和維護(hù),不和主工程產(chǎn)生耦合。同時(shí)由后臺(tái)服務(wù)器下發(fā),可即時(shí)在線更新不依賴客戶端版本。

皮膚包的加載過程:

SKinManger:

public void load(String skinPackagePath, final ILoaderListener callback) {
    
    new AsyncTask<String, Void, Resources>() {

        protected void onPreExecute() {
            if (callback != null) {
                callback.onStart();
            }
        };

        @Override
        protected Resources doInBackground(String... params) {
            try {
                if (params.length == 1) {
                    String skinPkgPath = params[0];
                    
                    File file = new File(skinPkgPath); 
                    if(file == null || !file.exists()){
                        return null;
                    }
                    
                    PackageManager mPm = context.getPackageManager();
                    PackageInfo mInfo = mPm.getPackageArchiveInfo(skinPkgPath, PackageManager.GET_ACTIVITIES);
                    skinPackageName = mInfo.packageName;

                    AssetManager assetManager = AssetManager.class.newInstance();
                    Method addAssetPath = assetManager.getClass().getMethod("addAssetPath", String.class);
                    addAssetPath.invoke(assetManager, skinPkgPath);

                    Resources superRes = context.getResources();
                    Resources skinResource = new Resources(assetManager,superRes.getDisplayMetrics(),superRes.getConfiguration());
                    
                    SkinConfig.saveSkinPath(context, skinPkgPath);
                    
                    skinPath = skinPkgPath;
                    isDefaultSkin = false;
                    return skinResource;
                }
                return null;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        };

        protected void onPostExecute(Resources result) {
            mResources = result;

            if (mResources != null) {
                if (callback != null) callback.onSuccess();
                notifySkinUpdate();
            }else{
                isDefaultSkin = true;
                if (callback != null) callback.onFailed();
            }
        };

    }.execute(skinPackagePath);
}

@Override
public void attach(ISkinUpdate observer) {
    if(skinObservers == null){
        skinObservers = new ArrayList<ISkinUpdate>();
    }
    if(!skinObservers.contains(observer)){
        skinObservers.add(observer);
    }
}

@Override
public void detach(ISkinUpdate observer) {
    if(skinObservers == null) return;
    if(skinObservers.contains(observer)){
        skinObservers.remove(observer);
    }
}

@Override
public void notifySkinUpdate() {
    if(skinObservers == null) return;
    for(ISkinUpdate observer : skinObservers){
        observer.onThemeUpdate();
    }
}

SKinManager為整個(gè)皮膚包的管理類,負(fù)責(zé)加載皮膚包文件,并得到該皮膚包的包名skinPackageName,和這個(gè)皮膚包的Resource對(duì)象skinResource,這樣整個(gè)皮膚包的資源文件我們就都可以拿到了。在加載得到皮膚包的Resource之后,通知每個(gè)注冊(cè)過(attach)的頁面(Activity),去刷新這些頁面所有保存過的需要換膚的View,進(jìn)行換膚操作。

切換時(shí)如何即時(shí)更新界面:

1、SkinBaseApplication:

public class SkinApplication extends BaseApplication {

@Override
public void onCreate() {
    super.onCreate();
    SkinManager.getInstance().init(this);
    SkinManager.getInstance().load();
  }
}

主要是進(jìn)行一些初始化的操作。

2、SkinBaseActivity:

public abstract class BaseActivity extends
    code.solution.base.BaseActivity implements ISkinUpdate, IDynamicNewView {

private SkinInflaterFactory mSkinInflaterFactory;

@Override
protected void onCreate(Bundle savedInstanceState) {

mSkinInflaterFactory = new SkinInflaterFactory();
LayoutInflaterCompat.setFactory(getLayoutInflater(), mSkinInflaterFactory);
super.onCreate(savedInstanceState);
changeStatusColor();
}

/**
 * dynamic add a skin view
 *
 * @param view
 * @param attrName
 * @param attrValueResId
 */
protected void dynamicAddSkinEnableView(View view, String attrName, int attrValueResId){
    mSkinInflaterFactory.dynamicAddSkinEnableView(this, view, attrName, attrValueResId);
}

@Override
public void onThemeUpdate() {
    if(!isResponseOnSkinChanging){
        return;
    }
    mSkinInflaterFactory.applySkin();
    changeStatusColor();
}

在這里使用了之前自定義的SkinInflaterFactory,來替換默認(rèn)的Factory,以達(dá)到截獲創(chuàng)建View,獲取View的屬性,與支持換膚的屬性進(jìn)行對(duì)比,進(jìn)行View換膚操作以及保存這些需要換膚的View到List<SkinItem>中,在下次換膚切換時(shí)對(duì)這些View進(jìn)行換膚的目的。

其中換膚操作執(zhí)行時(shí),會(huì)調(diào)用SKinManager.notifySKinUpdate方法

@Override
public void notifySkinUpdate() {
    if(skinObservers == null) return;
    for(ISkinUpdate observer : skinObservers){
        observer.onThemeUpdate();
    }
}

而這里的observer.onThemeUpdate里面主要是執(zhí)行這個(gè)Activity的下述方法:

public void onThemeUpdate() {
    if(!isResponseOnSkinChanging){
        return;
    }
    mSkinInflaterFactory.applySkin();
    changeStatusColor();
}

mSkinInflaterFactory.applySkin();即為SKinInflaterFactory的applySkin方法,

public void applySkin() {
    if (ListUtils.isEmpty(mSkinItems)) {
        return;
    }

    for (SkinItem si : mSkinItems) {
        if (si.view == null) {
            continue;
        }
        si.apply();
    }
  }

其中 mSKinItems即為當(dāng)前Acitivty通過xml 文件中skin:enbale進(jìn)行標(biāo)記的 及動(dòng)態(tài)dynamicAddSkinEnableView(...)添加的需要換膚的View的集合,這樣整個(gè)換膚的過程就完成了。

整體換膚框架類圖:

換膚架構(gòu)類圖.png

如何制作皮膚包:

1). 新建工程project
2). 將換膚的資源文件添加到res文件下,無java文件
3). 直接運(yùn)行build.gradle,生成apk文件(注意,運(yùn)行時(shí)Run/Redebug configurations 中Launch Options選擇launch nothing),否則build 會(huì)報(bào) no default Activty的錯(cuò)誤。
4). 將apk文件重命名如black.apk,重命名為black.skin防止用戶點(diǎn)擊安裝

在線換膚:

  1. 將皮膚包上傳到服務(wù)器后臺(tái)
  2. 客戶端根據(jù)接口數(shù)據(jù)下載皮膚包,進(jìn)行加載及客戶端換膚操作

結(jié)語:

至此,整個(gè)換膚流程的原理解析已經(jīng)全部講完了。本文針對(duì)基本的換膚原理流程做了解析,初步建立了一套相對(duì)完善的換膚框架。但是如何建立一套更加完善更加對(duì)其他開發(fā)者友善的換膚機(jī)制仍然是可以繼續(xù)研究的方向。比如如何更加安全的換膚,如何對(duì)代碼的侵入性做到最小(比如通過在配置文件中配置需要換膚的View的id name 而不是通過在xml文件中進(jìn)行標(biāo)記)等等,都是可以繼續(xù)研究的方向,以后有時(shí)間會(huì)繼續(xù)在這方面進(jìn)行探索。

因時(shí)間關(guān)系文章難免有疏漏,歡迎提出指正,謝謝。同時(shí)對(duì)換膚感興趣的童鞋可以參考以下鏈接:

1、Android-Skin-Loader
2、Android-skin-support
3、Android主題換膚 無縫切換

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 今天再給大家?guī)硪黄韶洝?Android的主題換膚 ,可插件化提供皮膚包,無需Activity的重啟直接實(shí)現(xiàn)無縫...
    _SOLID閱讀 100,025評(píng)論 147 1,120
  • 前言 Android換膚技術(shù)已經(jīng)是很久之前就已經(jīng)被成熟使用的技術(shù)了,然而我最近才在學(xué)習(xí)和接觸熱修復(fù)的時(shí)候才看到。在...
    靜默加載閱讀 3,120評(píng)論 1 8
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,552評(píng)論 25 708
  • 我知道自己一直不斷地在計(jì)劃和放棄的程序中循環(huán),沒有好的成果,但又從未間斷運(yùn)行。 我知道,我為什么不能取得卓越的成績(jī)...
    柴柴cc閱讀 199評(píng)論 0 0
  • 今天要回復(fù)一個(gè)微信后臺(tái)的提問 hi,我是一個(gè)剛畢業(yè)的新人。最近在糾結(jié),大公司和創(chuàng)業(yè)團(tuán)隊(duì)我該選哪一家?待遇和福利都相...
    肥寒925閱讀 585評(píng)論 0 1