轉(zhuǎn)載請(qǐng)注明出處,感謝您的支持。同時(shí)瞒滴,歡迎加入移動(dòng)開發(fā)學(xué)習(xí)交流qq群 : 450302004父晶,互相學(xué)習(xí)哮缺。
文章來源:【chenyk的簡書】http://www.reibang.com/p/282b0d1c142c
前言
在項(xiàng)目的開發(fā)過程中,對(duì)于資源的使用甲喝,無非有以下幾種情況:
1尝苇、Application使用自身資源
2、Application使用Module資源
3埠胖、Module使用自身或另外的Module資源
4糠溜、Module使用Application資源
前3項(xiàng)在這里就不過多介紹,這里主要說下第4項(xiàng)直撤,有些時(shí)候我們需要在抽取的module中使用到Application的資源非竿,而且我們并不想在Module中重新定義。如果直接調(diào)用的話谋竖,是調(diào)用不到的红柱。所以我們需要通過getIdentifier()方法來實(shí)現(xiàn),具體如下:
/**
* 獲取context中對(duì)應(yīng)類型的資源id
*
* @param context
* @param type 資源類型蓖乘,"layout","string","drawable","color"等
* @param resName
* @return
*/
private static int getResId(Context context, String type, String resName) {
return context.getResources().getIdentifier(resName, type, context.getPackageName());
}
舉個(gè)栗子豹芯,在下圖中,包含2個(gè)Application(app/doctor)和5個(gè)Module(calendarview/commlib/date_picker/MPChartLib/NativeH5Lib)驱敲,如果要在commlib使用app的資源铁蹈,就使用以上的方法去獲取。
項(xiàng)目結(jié)構(gòu).png
調(diào)用方式
調(diào)用方法非常簡單众眨,只需傳入context和res名稱即可握牧,如下所示:
ResourceUtil.getColorResId(this, "colorPrimary"); //colorPrimary是color.xml文件中定義的資源
完整的工具類
import android.content.Context;
/**
* Created by chenyk on 2017/6/2.
* 資源工具類
* 功能:module中根據(jù)context動(dòng)態(tài)獲取application中對(duì)應(yīng)資源文件
*/
public class ResourceUtil {
/**
* 獲取布局資源
*
* @param context
* @param resName
* @return
*/
public static int getLayoutResId(Context context, String resName) {
return getResId(context, "layout", resName);
}
/**
* 獲取字符串資源
*
* @param context
* @param resName
* @return
*/
public static int getStringResId(Context context, String resName) {
return getResId(context, "string", resName);
}
/**
* 獲取Drawable資源
*
* @param context
* @param resName
* @return
*/
public static int getDrawableResId(Context context, String resName) {
return getResId(context, "drawable", resName);
}
/**
* 獲取顏色資源
*
* @param context
* @param resName
* @return
*/
public static int getColorResId(Context context, String resName) {
return getResId(context, "color", resName);
}
/**
* 獲取id文件中資源
*
* @param context
* @param resName
* @return
*/
public static int getIdRes(Context context, String resName) {
return getResId(context, "id", resName);
}
/**
* 獲取數(shù)組資源
*
* @param context
* @param resName
* @return
*/
public static int getArrayResId(Context context, String resName) {
return getResId(context, "array", resName);
}
/**
* 獲取style中資源
*
* @param context
* @param resName
* @return
*/
public static int getStyleResId(Context context, String resName) {
return getResId(context, "style", resName);
}
/**
* 獲取context中對(duì)應(yīng)類型的資源id
*
* @param context
* @param type
* @param resName
* @return
*/
private static int getResId(Context context, String type, String resName) {
return context.getResources().getIdentifier(resName, type, context.getPackageName());
}
}