首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 代碼設置 ImageView src:drawable 資源獲取方法

     編輯:程式設計綜合問答

核心 API

ImageView.setImageResource(int resId) —— 直接傳 R.drawable.xxx 最簡單。

其他可用方法

方法參數適用場景
setImageResource@DrawableRes int靜態資源 ID,最常用
setImageDrawableDrawable已有 Drawable 對象(如從 Bitmap 創建)
setImageBitmapBitmap動態生成/下載的圖片
setImageURIUriContent Provider / 文件路徑

獲取 Drawable 對象示例


// 1. 從資源 ID 獲取 Drawable (API 21+ 需 Theme)
Drawable drawable = ContextCompat.getDrawable(context, R.drawable.my_image);
imageView.setImageDrawable(drawable);

// 2. 從資源獲取 Bitmap
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.my_image);
imageView.setImageBitmap(bitmap);

// 3. 從 assets/raw 讀取
InputStream is = getResources().openRawResource(R.raw.my_image);
Drawable drawable2 = Drawable.createFromStream(is, null);
imageView.setImageDrawable(drawable2);

注意

  • 不要在 UI 線程解碼大圖,用 Glide/Picasso 或 BitmapFactory.Options.inSampleSize。
  • R.drawable.xxx 本質是 int,非 Drawable 對象。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved