歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android getResources的作用和需要注意點

Android getResources的作用和需要注意點

日期:2017/3/1 11:08:53   编辑:Linux編程

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

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

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

一開始不是很理解為什麼用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, 40, 40, mPaint);

  1. InputStream is = getResources().openRawResource(R.drawable.icon);
  2. Bitmap mBitmap = BitmapFactory.decodeStream(is);
  3. Paint mPaint = new Paint();
  4. canvas.drawBitmap(mBitmap, 40, 40, 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、可以用作成員變量,構造傳入或方法參數傳入。就可以了。

Copyright © Linux教程網 All Rights Reserved