標籤:
轉 http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2012/1201/655.html
一.基本介紹
資料包package:android.content.res
主要類:Resources
InputStream openRawResource(int id) 擷取資源的資料流,讀取資源資料
把一個圖片資源,添加你的檔案到你工程中res/drawable/目錄中去,可以在代碼或XML布局中,引用它也可以用資源編號,比如你選擇一個檔案只要去掉尾碼就可以了(例如:mm_image.png 引用它是就是mm_image)。
當需要使用的xml資源的時候,就可以使用context.getResources().getDrawable(R....資源的地址如:R.String.ok);
當你方法裡面沒有Context參數,可以 this.getContext().getResources();這樣就可以了。
下面詳細說明一下使用情境:
1、需要使用getResource()的時候一定要注意
必須要有Context, 這個一般的service或者activity即帶有
可以用作成員變數,構造傳入或方法參數傳入就可以了
2、引用xml檔案時,可能通過:
getResources().getXml()獲的XML原始檔案,然後再得到XmlResourceParser對象
XmlResourceParser xrp = mRes.getXml(R.xml.personal);
而利用R....可以指定檔案夾下面的某個xml檔案進行載入使用
3、其它的一些檔案讀取方法
a、把資源檔放到應用程式的/raw/raw下,那麼就可以在應用中使用getResources擷取資源後,
以openRawResource方法(不帶尾碼的資源檔名)開啟這個檔案
Resources myResources = getResources(); InputStream myFile = myResources.openRawResource(R.raw.xx_filename);
與普通java程式一樣,android提供了openFileInput和openFileOutput方法來讀取裝置上的檔案
InputStream fs =this.getResources().openRawResource(R.raw.index.htm); (資源檔名為index.html, 不需要帶尾碼.htm) InputStreamReader read = new InputStreamReader (fs,"utf-8"); BufferedReader in = new BufferedReader(read);
b、讀取res/drawable目錄下的png或者bmp
//得到Resources對象 Resources r = this.getContext().getResources(); //以資料流的方式讀取資源 Inputstream is = r.openRawResource(R.drawable.mm_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);
使用getResource()的時候注意
1、必須要有Context呀 2、可以用作成員變數,構造傳入或方法參數傳入。就可以了。
Android --- 讀取系統資源函數getResources()小結