码迷,mamicode.com
首页 > 移动开发 > 详细

赵雅智_Android的getResources()资源引用

时间:2017-05-19 23:56:00      阅读:258      评论:0      收藏:0      [点我收藏+]

标签:操作   int   地址   oid   选择   resources   new   text   put   

今天做一个Android的刮刮乐项目。里面用到非常多的地方用到了getResources。

<span style="font-size:12px;">		// 获得图片
		//參数1:res是资源的引用,參数2:id是图片的id
		after = BitmapFactory.decodeResource(getResources(), R.drawable.b);
		before = BitmapFactory.decodeResource(getResources(), R.drawable.a);</span>

一開始不是非常理解为什么用 getResources()这种方法就能够获取存在系统的资源。

于是看了一下文档和翻阅了一下资料:

数据包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、能够用作成员变量,构造传入或方法參数传入。就能够了。


把资源文件放到应用程序的/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);  


赵雅智_Android的getResources()资源引用

标签:操作   int   地址   oid   选择   resources   new   text   put   

原文地址:http://www.cnblogs.com/zhchoutai/p/6880435.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!