由于android在打入jar包的時(shí)候是不予許攜帶res等資源文件的列疗,所以我們采用如下方式去使用資源文件。
1把圖片或者資源放入assert文件夾中俺附,打包成jar包的時(shí)候勾選assert文件
如 我在assert文件中放入了一個(gè)web_delete.png的圖片
給按鈕設(shè)置背景圖片
imageButton.setImageBitmap(stringBitmap(context,"web_delete.png"));
設(shè)置圖片的方法
public static Bitmap stringBitmap(Context context, String string) {
AssetManager assets = context.getAssets();
InputStream is = null;
try {
is = assets.open(string);
} catch (IOException e) {
e.printStackTrace();
}
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeStream(is, null, options);
return bitmap;
}
很多時(shí)候我們需要打包的不止是圖片等多媒體文件肥卡,我們需要打包XML布局等文件或者有id的文件的時(shí)候怎么辦呢?我觀察了友盟等jar包發(fā)現(xiàn)他們都是把資源文件暴露給引用jar包的工程事镣,放到其res文件中步鉴。
如。我們把需要用到的aaa.png放到了B工程的res文件中璃哟,B工程引用了 A jar包氛琢。
在A中需要給某個(gè)按鈕加上背景圖片代碼如下:
int bg_id = context.getResources().getIdentifier("aaa",
"drawable", context.getPackageName());
if (bg_id != 0) {
imageButton.setBackgroundResource(bg_id);
}
第二個(gè)參數(shù)type:R其中的內(nèi)部類(lèi)名,如"drawable","string","color","dimen","layout"等随闪,這也是我們常用的關(guān)于界面所需要獲取的數(shù)據(jù)類(lèi)型
順便補(bǔ)充一點(diǎn)知識(shí)阳似,當(dāng)jar包中需要使用動(dòng)態(tài)布局的時(shí)候,我們通常使用LayoutParams,而這個(gè)屬性通常都是用其父類(lèi)下的LayoutParams铐伴,當(dāng)我們?yōu)槠湓O(shè)置度量單位時(shí)它接受的是PX單位撮奏,而我們?cè)赬ML文件中通常都是使用DP作為單位的俏讹,所以提供了以下兩個(gè)方法作為單位轉(zhuǎn)換。
public static int dp2px(Context context, float dipValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}
public static int px2dp(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}