Android获取res目录下的资源
在项目中,我们经常需要获取res目录下的各种资源,如图片,文字,声音,颜色,布局。我将网络上一些资料和项目结合做一个简单的说明。
一、获取图片
//得到application对象
ApplicationInfo appInfo = getApplicationInfo();
//得到该图片的id(name 是该图片的名字,"drawable" 是该图片存放的目录,appInfo.packageName是应用程序的包)
int resID = getResources().getIdentifier(name, "drawable", appInfo.packageName);
//代码如下
public Bitmap getRes(String name) {
ApplicationInfo appInfo = getApplicationInfo();
int resID = getResources().getIdentifier(name, "drawable", appInfo.packageName);
return BitmapFactory.decodeResource(getResources(), resID);
}
二、获取文字
在activity中,或者在service中,直接调用getString(resId)进行获取就可以了
/** * 不在activity中,或者不在service中,使用此方法,获取res目录下的音频文件 * */ public String getResStr(Context context, int resId){ return context.getString(resId); }
三、获取颜色
/**
* 不在activity中,或者不在service中,使用此方法,获取res目录下的颜色
* 返回参数为整形,颜色本身就是一串数字
* */
public int getResColor(Context context, int resId){
return context.getResources().getColor(resId);
}
四、获取布局
/**
* 我的理解Android framework至少应该提供一些获取Resource的api才对,详细看了sdk docs始终没找到相应的方法.
* 也许有,在其父类中,定义也说不准,我是没找到. 那么这里就不得不需要借助一个抽象类 LayoutInflater
* inflate获取出来的对象是View,所有layout布局,均是继承View,做向上转型完全没有问题.
* 但是它其实真是身份还是Layout,具体是那一种layout就通过强制类型转换,转换成某种类型.
*/
public View getResLay() {
LayoutInflater inflater = (LayoutInflater) this
.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.devicelistactivity, null);
RelativeLayout rlayout = (RelativeLayout) layout;
rlayout.addView(layout);
return rlayout;
}
五、文件的获取(包括了图片,音频等,通用方法)
下面以文本文件做说明,例如资源文件 sample.txt 位于 $PROJECT_HOME/res/ raw目录下,可以在 Activity 中通过
Context.getResources().openRawResource(R.raw.sample);
方法获取输入流。
注意:如果资源文件是文本文件则需要考虑文件的编码和换行符。建议使用UTF-8和Unix换行符。
例子:
/**
* 从resources中的raw 文件夹中获取文本文件并读取数据
* @param encoding 编码格式,如utf-8
* @param resid 资源目录id
* */
public String getFromRaw(String encoding,int resid){
String result = "";
try {
InputStream in = getResources().openRawResource(resid);
//获取文件的字节数
int lenght = in.available();
//创建byte数组
byte[] buffer = new byte[lenght];
//将文件中的数据读到byte数组中
in.read(buffer);
result = EncodingUtils.getString(buffer, encoding);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}