趙雅智_Android的getResources()資源引用

來源:互聯網
上載者:User

標籤:android   getresources   

今天做一個Android的刮刮樂項目,裡面用到很多的地方用到了getResources。

<span style="font-size:12px;">// 獲得圖片//參數1:res是資源的引用,參數2:id是圖片的idafter = BitmapFactory.decodeResource(getResources(), R.drawable.b);before = BitmapFactory.decodeResource(getResources(), R.drawable.a);</span>

一開始不是很理解為什麼用 getResources()這個方法就可以擷取存在系統的資源。於是看了一下文檔和翻閱了一下資料:

資料包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、可以用作成員變數,構造傳入或方法參數傳入。就可以了。


把資源檔放到應用程式的/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();  
方法2:
InputStream is = getResources().openRawResource(R.drawable.icon);  Bitmap mBitmap = BitmapFactory.decodeStream(is);  Paint mPaint = new Paint();  canvas.drawBitmap(mBitmap, 40, 40, mPaint);  


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.