2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > android 资源文件获取啥退 重拾Android之路之获得各种资源文件的方法

android 资源文件获取啥退 重拾Android之路之获得各种资源文件的方法

时间:2021-04-21 09:20:04

相关推荐

android 资源文件获取啥退 重拾Android之路之获得各种资源文件的方法

引言

通常我们会在项目中频繁获取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);

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。