引言

通常我们会在项目中频繁获取color、raw、drawable、mipmap、string等资源文件。因此,今天整理下获取资源文件的工具类方法。

最新通用方法

ContextCompat.getColor(this,R.color.activity_bg);

ContextCompat.getDrawable(this,R.drawable.leak_canary_icon);

最近在写程序的时候遇到了一个问题,就是textview已经指定了drawableTop的图片,但是需要在Java中重新更换一张图片

//获取更换的图片

Drawable drawable=getResources().getDrawable(R.drawable.close);

//setBounds(x,y,width,height)

drawable.setBounds(0,0,drawable.getMinimumWidth(),drawable.getMinimumHeight());

//mDownLoad是控件的名称,setCompoundDrawables(left,top,right,bottom)

mDownLoad.setCompoundDrawables(null,drawable,null,null);

mDownLoad.setTextColor(ContextCompat.getColor(this, R.color.tap_grey));

如果直接使用textView.setCompoundDrawables(null, ContextCompat.getDrawable(this, R.mipmap.homepage_fill_unchecked), null, null);方法,即不设置setBounds方法,将不会显示图片资源。(这是个坑,原理是啥,暂时不去深究)

图片来源于drawable

textView.setBackgroundDrawable(getResources().getDrawable(R.drawable.search));

textView..setBackgroundResource(R.drawable.search);

转换字符串为int(颜色)

textView.setBackgroundColor(Color.parseColor("#F5F5DC"));

使用String资源

this.getResources().getString(R.string.setIP);

简单示例

1、

Resources resources = mContext.getResources();

Drawable drawable = resources.getDrawable(R.drawable.a);

imageview.setBackground(drawable);

2、

Resources r = this.getContext().getResources();

Inputstream is = r.openRawResource(R.drawable.my_background_image);

BitmapDrawable bmpDraw = new BitmapDrawable(is);

Bitmap bmp = bmpDraw.getBitmap();

3、

Bitmap bmp=BitmapFactory.decodeResource(r, R.drawable.icon);

Bitmap newb = Bitmap.createBitmap( 300, 300, Config.ARGB_8888 );

4、

InputStream is = getResources().openRawResource(R.drawable.icon);

Bitmap mBitmap = BitmapFactory.decodeStream(is);

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐