Android换肤

来源:互联网 发布:吗288清零软件 编辑:程序博客网 时间:2024/05/17 06:30
换肤有多种方案,但用到的最终方法都是一样的,就是用新的Resource读取apk里的资源
    /**
     * 生成皮肤包的AssetManager
     *
     *@paramapkPath
     *@return
     */
    privatestaticAssetManager createAssetManager(String apkPath) {
         try{
             AssetManager assetManager = AssetManager.class.newInstance();
             try{
                 AssetManager.class.getDeclaredMethod("addAssetPath",
                          String.class).invoke(assetManager, apkPath);
             }catch(Throwable th) {
                 th.printStackTrace();
             }
             returnassetManager;
         }catch(Throwable th) {
             th.printStackTrace();
         }
         returnnull;
    }
    
    /**
     * 获取Bundle中的资源
     *@paramcontext
     *@paramapkPath
     *@return
     */
   publicstaticResources getBundleResource(Context context, String apkPath){
        AssetManager assetManager =createAssetManager(apkPath);
       returnnewResources(assetManager, context.getResources().getDisplayMetrics(), context.getResources().getConfiguration());
    }
在如何使用新的Resource时,就有多种方案,比如反射context里的resource,直接把设置为新的,但这种要注意到apk的更新,另外一种,是自己弄个资源管理器,每次都从资源管理器里读取资源,不使用R
如调用string类型的名为name的字符串,defPackage为apk路径
/**
 * Return a resource identifier for the given resource name.  A fully
 * qualified resource name is of the form "package:type/entry".  The first
 * two components (package and type) are optional if defType and
 * defPackage, respectively, are specified here.
 * 
 * <p>Note: use of this function is discouraged.  It is much more
 * efficient to retrieve resources by identifier than by name.
 * 
 * @param name The name of the desired resource.
 * @param defType Optional default resource type to find, if "type/" is
 *                not included in the name.  Can be null to require an
 *                explicit type.
 * @param defPackage Optional default package to find, if "package:" is
 *                   not included in the name.  Can be null to require an
 *                   explicit package.
 * 
 * @return int The associated resource identifier.  Returns 0 if no such
 *         resource was found.  (0 is not a valid resource ID.)
 */
public int getIdentifier(String nameString defTypeString defPackage) {
    if (name == null) {
        throw new NullPointerException("name is null");
    }
    try {
        return Integer.parseInt(name);
   catch (Exception e) {
        // Ignore
    }
    return mAssets.getResourceIdentifier(namedefTypedefPackage);
}
0 0