寫檔案管理器的時候,處處都要取用圖示與字串,getResources() 因此成了最常打交道的夥伴。
Drawable currentIcon = null; ... currentIcon = getResources().getDrawable(R.drawable.folder); ... currentIcon = getResources().getDrawable(R.drawable.image);
一開始我不太理解,為什麼單靠這個方法就能拿到打包進程式的資源。翻過文件與資料後才理出頭緒:資源在編譯時被編入 R 類,Resources 就是那本索引。
把檔案放進 res/raw,就能用「不帶副檔名的資源名」開啟:
Resources myResources = getResources(); InputStream myFile = myResources.openRawResource(R.raw.myfilename);
簡寫版本,例如要讀 kb.html(引用時不帶 .html):
InputStream is = this.getResources().openRawResource(R.raw.kb); InputStreamReader read = new InputStreamReader(is, "gb2312"); BufferedReader in = new BufferedReader(read);
若只是要讀設備上的檔案,Android 也提供了和傳統 Java 相近的 openFileInput / openFileOutput。
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);
資源所在的套件是 android.content.res,主要類別為 Resources,核心方法 InputStream openRawResource(int id) 取得資源的資料流。
放進 res/drawable/ 的圖片,引用時去掉副檔名即可,例如 my_image.png 寫成 my_image;XML 中則用 context.getResources().getDrawable(R.…)。如果所在方法沒有 Context 參數,用 this.getContext().getResources() 也能拿到。
最後提醒兩件事:使用 getResources() 一定要具備 Context;它可以存成成員變數,或透過建構子、方法參數傳入,三種方式都行。