您的位置:首页 > 移动开发 > Android开发

Android换肤

2016-05-16 11:19 627 查看
换肤有多种方案,但用到的最终方法都是一样的,就是用新的Resource读取apk里的资源
[align=left] /**[/align]
[align=left] * 生成皮肤包的AssetManager[/align]
[align=left] *[/align]
*
@param
apkPath
*
@return
[align=left] */[/align]
private
static
AssetManager createAssetManager(String apkPath) {

try
{
AssetManager assetManager = AssetManager.class
.newInstance();

try
{
AssetManager.
class.getDeclaredMethod("addAssetPath"
,
String.
class).invoke(assetManager, apkPath);
}
catch
(Throwable th) {
[align=left] th.printStackTrace();[/align]
[align=left] }[/align]

return
assetManager;
}
catch
(Throwable th) {
[align=left] th.printStackTrace();[/align]
[align=left] }[/align]

return
null
;
[align=left] }[/align]
[align=left] [/align]

/**
[align=left] * 获取Bundle中的资源[/align]
*
@param
context
*
@param
apkPath
*
@return
[align=left] */[/align]

public
static
Resources getBundleResource(Context context, String apkPath){
AssetManager assetManager =
createAssetManager(apkPath);

return
new
Resources(assetManager, context.getResources().getDisplayMetrics(), context.getResources().getConfiguration());
[align=left] }[/align]
[align=left]在如何使用新的Resource时,就有多种方案,比如反射context里的resource,直接把设置为新的,但这种要注意到apk的更新,另外一种,是自己弄个资源管理器,每次都从资源管理器里读取资源,不使用R[/align]
[align=left]如调用string类型的名为name的字符串,defPackage为apk路径[/align]

/**

* 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 name, String defType, String defPackage) {

if (name == null) {

throw new NullPointerException("name is null");

}

try {

return Integer.parseInt(name);

} catch (Exception e) {

// Ignore

}

return mAssets.getResourceIdentifier(name, defType, defPackage);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: