更換皮膚的方式有很多種,有更換背景圖片的(圖片來源于程序資源文件、sdCard、網絡下載)、有更換theme樣式的、也有apk的等等。
用apk的方式更換程序皮膚,這樣的方式,方便,簡單,而且使主程序的apk包較小。
先下載皮膚apk包,安裝,然后使現在的程序讀取新安裝的apk包中的資源文件,下次再打開程序時,照舊讀取的是上次設置的apk的資源,如果主題apk被卸載,那末就讀取的是默許的資源。
核心代碼(完全代碼見項目緊縮包)以下:
主程序:
讀取已安裝了的皮膚包的包名、利用圖標和利用名稱,固然最重要的實包名,這樣可以通過包名,去讀取當前皮膚包中的其它資源的資源名稱,從而去加載。
private Runnable serachSkin = new Runnable() {
@Override
public void run() {
PackageManager manager = context.getPackageManager();
List<PackageInfo> packages = manager.getInstalledPackages(PackageManager.PERMISSION_GRANTED);
List<PackageInfo> skins = new ArrayList<PackageInfo>();
for (PackageInfo info : packages) { // 遍歷已安裝的皮膚包
if (info.packageName.startsWith("com.theme.")) { // 與皮膚包的包名對應便可
skins.add(info);
}
}
if (skins.size() > 0) {
Message msg = mHandler.obtainMessage();
msg.obj = skins;
msg.setData(new Bundle());
msg.what = MESSAGE_SEARCHED_SKIN;
mHandler.sendMessage(msg);
} else {
mHandler.sendEmptyMessage(MESSAGE_SEARCHED_SKIN_FOR_NONTHING);
}
}
};
this.setOnThemeChangedListener(new OnThemeChangedListener() {
@Override
public void onChanged(String themePackageName) {
Log.i("", "themePackageName :: " + themePackageName);
try {
Context themeContext = ThemeSecondActivity.this.createPackageContext(themePackageName, Context.CONTEXT_IGNORE_SECURITY);
Resources themeResources = themeContext.getResources();
setControlsStyle(themePackageName, themeResources);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
});
/**
* 設置控件新皮膚
* @param themePackageName 皮膚包的包名
* @param themeResources 皮膚包的資源
*/
private void setControlsStyle(String themePackageName, Resources themeResources) {
Log.i("", "themePackageName :: " + themePackageName);
button.setBackground(themeResources.getDrawable(themeResources.getIdentifier("button_selector", "drawable", themePackageName))); // 確保drawable資源文件中有button_selector文件
gridview.setBackgroundColor(themeResources.getColor(themeResources.getIdentifier("background_gridview", "color", themePackageName)));
}
找了很久的apk換膚,類似新浪微博或QQ換膚,找到的案例只是簡單的在當前項目中更換主題,或是apk包,但放置到自己的項目中時,拋出空指針或資源文件不存在的異常。
糾其緣由,由于資源文件沒有找到,在當前項目中用的是getDrawable(R.drawable.xx)方式來獲得圖片,這類方式是根據R.drawable.xx對應的1個int值(int值在工程中的gen文件夾下的R.java的class類中)來辨認并加載的,這樣要確保主工程與皮膚工程對應的兩個值是1樣的,如果不1樣,便可能出現錯位(int值對應到其它的資源),固然還有可能致使空指針或找不到資源文件(int值不存在)。
決解方式是,確保當前讀取的res資源是皮膚包的資源,讀取方式是:
Context themeContext = ThemeSecondActivity.this.createPackageContext(themePackageName,Context.CONTEXT_IGNORE_SECURITY);
Resources themeResources = themeContext.getResources();
項目緊縮包下載地址:http://download.csdn.net/detail/xue_wei_love/8581235
說明:apk方式更換主題:包括多個頁面更換,多個資源更換(可以色彩值、圖片、xml文件等自定義資源文件)。 緊縮中中包括4個工程,說明以下: SkinTheme是主工程,SkinRed是紅色主題包,SkinGreen是綠色主題包,SkinBlue是藍色主題包。
參考:
http://www.eoeandroid.com/thread⑴02060⑴⑴.html
http://bbs.csdn.net/topics/390311059
http://www.2cto.com/kf/201204/129474.html
http://blog.csdn.net/vincent_czz/article/details/7276118
http://www.javaapk.com/source/417.html#
http://down.51cto.com/data/622207