Android getResources的作用和需要注意点


做一个Android的文件管理器,里面用到很多的地方用到了getResources。

 
  1. Drawable currentIcon = null;  
  2.   
  3. ………………  
  4.   
  5. currentIcon = getResources().getDrawable(R.drawable.folder);  
  6.   
  7. ………………  
  8.   
  9. currentIcon = getResources().getDrawable(R.drawable.image);  
  10.   
  11. …………  

 

  1. Drawable currentIcon = null;  
  2.   
  3. ………………  
  4.   
  5. currentIcon = getResources().getDrawable(R.drawable.folder);  
  6.   
  7. ………………  
  8.   
  9. currentIcon = getResources().getDrawable(R.drawable.image);  
  10.   
  11. …………  
 

一开始不是很理解为什么用c getResources()这个方法就可以获取存在系统的资源。于是看了一下文档和翻阅了一下资料:

例如:把资源文件放到应用程序的/raw/raw下,那么就可以在应用中使用getResources获取资源后,以openRawResource方法(不带后缀的资源文件名)打开这个文件。例如:

 
  1. Resources myResources = getResources();  
  2. InputStream myFile = myResources.openRawResource(R.raw.myfilename);  

和传统的java文件操作一样,在android Api中提供了openFileInput和openFileOutput方法来读取设备上的文件。

简写

 
  1. InputStream fs =this.getResources().openRawResource(R.raw.kb); (资源文件名为kb.html, 不需要带后缀.html)  
  2. InputStreamReader read = new InputStreamReader (fs,”gb2312″);  
  3. BufferedReader in = new BufferedReader(read);  

 

 
  1. InputStream fs =this.getResources().openRawResource(R.raw.kb); (资源文件名为kb.html, 不需要带后缀.html)  
  2. InputStreamReader read = new InputStreamReader (fs,”gb2312″);  
  3. BufferedReader in = new BufferedReader(read);  

读取res/drawable目录下的png或者bmg

 
  1. //得到Resources对象   
  2. Resources r = this.getContext().getResources();  
  3. //以数据流的方式读取资源   
  4. Inputstream is = r.openRawResource(R.drawable.my_background_image);  
  5. BitmapDrawable bmpDraw = new BitmapDrawable(is);  
  6. Bitmap bmp = bmpDraw.getBitmap();  

 

 
  1. //得到Resources对象   
  2. Resources r = this.getContext().getResources();  
  3. //以数据流的方式读取资源   
  4. Inputstream is = r.openRawResource(R.drawable.my_background_image);  
  5. BitmapDrawable bmpDraw = new BitmapDrawable(is);  
  6. Bitmap bmp = bmpDraw.getBitmap();  

或者

 
  1. InputStream is = getResources().openRawResource(R.drawable.icon);  
  2. Bitmap mBitmap = BitmapFactory.decodeStream(is);  
  3. Paint mPaint = new Paint();  
  4. canvas.drawBitmap(mBitmap, 4040, mPaint);  

 

 
  1. InputStream is = getResources().openRawResource(R.drawable.icon);  
  2. Bitmap mBitmap = BitmapFactory.decodeStream(is);  
  3. Paint mPaint = new Paint();  
  4. canvas.drawBitmap(mBitmap, 4040, mPaint);  

 数据包package:android.content.res
主要类:Resources

InputStream openRawResource(int id) 获取资源的数据流,读取资源数据

把一个图片资源,添加你的文件到你工程中res/drawable/目录中去,从这里,你就可以引用它到你的代码或你的XML布局中,也就是说,引用它也可以用资源编号,比如你选择一个文件只要去掉后缀就可以了(例如:my_image.png 引用它是就是my_image)。

当需要使用的xml资源的时候,就可以使用context.getResources().getDrawable(R....资源的地址如:R.String.ok);

当你方法里面没有Context参数,可以 this.getContext().getResources();这样就可以了。


注意,使用getResource()的时候注意

1、必须要有Context呀 2、可以用作成员变量,构造传入或方法参数传入。就可以了。

相关内容