Android换肤处理

今天被点九图的处理整的晕头转向的,主要原因是现在要处理的点九图是需要从后台下载而不是直接指定到资源文件中,网上找了不少处理都没有收到很好的效果,这里我先主要介绍一下通过下载apk,然后从apk中获取资源文件的方式。
先看下效果图吧。
加载前
pre
加载后
after
这里我们明显的看到加载前跟加载后的效果背景框。9图加载后能完美设置到控件上(这里我们重点关注下红框里面的内容,虽然美女很漂亮)
1.首先是写工具类


public class ResUtils {
    @SuppressLint("PrivateApi")
    public static Drawable getExtraResources(Context context, String resouseApkPath, String extraResName, String extraRPackage) {
        try {
            Resources superRes = context.getResources(); // 读取本地的一个 .skin里面的资源
            AssetManager asset = AssetManager.class.newInstance();// 创建AssetManager
            Method method = AssetManager.class.getDeclaredMethod("addAssetPath", String.class);  // method.setAccessible(true); 如果是私有的
            method.invoke(asset, resouseApkPath);  // 反射执行方法 getApplicationContext().getFilesDir().getAbsolutePath()+ File.separator + "red.skin"
            Resources resource = new Resources(asset, superRes.getDisplayMetrics(), superRes.getConfiguration());
            int drawableId = resource.getIdentifier(extraResName, "drawable", extraRPackage);  // 获取资源 id  "affinity_show_guide"  "com.showself.ui"
            return resource.getDrawable(drawableId);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}

主要思路是通过反射调用AssertManager的addAssetPath方法获取到resource 对象在通过调用resource的getIdentifier方法获取我们的drawable
这里需要注意几点
1.传递的参数resouseApkPath是我们下载的承载皮肤的apk路径(需要从后台下载)
2.extraResName这个参数是我们要调用的res的名称如R.drawable.aas 那么这个参数填写aas
3.extraRPackage这个参数是我们下载的apk包R这个类的包名如下载apk的包名为 com.tta,R那这里的参数为com.tta

2.最后一步就是调用了也是很简单代码如下

public void onClick(View v) {
        Toast.makeText(this,"点击",Toast.LENGTH_LONG).show();
       Drawable drawable=  ResUtils.getExtraResources(this, getApplicationContext().getFilesDir().getAbsolutePath()+ File.separator + "red.skin",
                "chat_left_bubble_message_bg","com.showself.ui");
        if (drawable!=null){
            RelativeLayout rl_content= (RelativeLayout) findViewById(R.id.rl_content);
            rl_content.setBackgroundDrawable(drawable);
        }
    }

是不是很简单,希望这篇博客能帮助到迷茫的小伙伴。

猜你喜欢

转载自blog.csdn.net/u011048906/article/details/80586827