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);
總結
以上是默认站点為你收集整理的android 资源文件获取啥退,重拾Android之路之获得各种资源文件的方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何用c语言验证一个定理,验证动量定理方
- 下一篇: 如何将多个Android Wear手表与