今天做一個Android的文件管理器,里面用到非常多的地方用到了getResources。
Drawable currentIcon = null; currentIcon = getResources().getDrawable(R.drawable.folder); currentIcon = getResources().getDrawable(R.drawable.image);
一開始不是非常理解為什么用 getResources()這種方法就能夠獲取存在系統的資源。於是看了一下文檔和翻閱了一下資料:
比如:把資源文件放到應用程序的/raw/raw下,那么就能夠在應用中使用getResources獲取資源后,以openRawResource方法(不帶后綴的資源文件名稱)打開這個文件。比如:
Resources myResources = getResources(); InputStream myFile = myResources.openRawResource(R.raw.myfilename);
和傳統的java文件操作一樣,在android Api中提供了openFileInput和openFileOutput方法來讀取設備上的文件。
簡寫
InputStream fs =this.getResources().openRawResource(R.raw.kb); (資源文件名稱為kb.html, 不須要帶后綴.html) InputStreamReader read = new InputStreamReader (fs,”gb2312″); BufferedReader in = new BufferedReader(read);
讀取res/drawable文件夾下的png或者bmg
//得到Resources對象 Resources r = this.getContext().getResources(); //以數據流的方式讀取資源 Inputstream is = r.openRawResource(R.drawable.my_background_image); BitmapDrawable bmpDraw = new BitmapDrawable(is); Bitmap bmp = bmpDraw.getBitmap();
或者
InputStream is = getResources().openRawResource(R.drawable.icon); Bitmap mBitmap = BitmapFactory.decodeStream(is); Paint mPaint = new Paint(); canvas.drawBitmap(mBitmap, 40, 40, mPaint);
數據包package:android.content.res
主要類:Resources
InputStream openRawResource(int id) 獲取資源的數據流,讀取資源數據
把一個圖片資源,加入你的文件到你project中res/drawable/文件夾中去,從這里,你就能夠引用它到你的代碼或你的XML布局中,也就是說,引用它也能夠用資源編號,比方你選擇一個文件僅僅要去掉后綴就能夠了(比如:my_image.png 引用它是就是my_image)。
當須要使用的xml資源的時候,就能夠使用context.getResources().getDrawable(R....資源的地址如:R.String.ok);
當你方法里面沒有Context參數,能夠 this.getContext().getResources();這樣就能夠了。
注意,使用getResource()的時候注意
1、必須要有Context呀
2、能夠用作成員變量,構造傳入或方法參數傳入。就能夠了。