在Java代碼中雖然可以直接通過R.drawable.圖片名(注:不帶后綴)引用,但難免還有使用相對路徑引用的需求(比如我...),所以特以記之
注:我引用的圖片資源是eclipse自帶的機器人圖片
代碼如下:

package com.example.fragmenttest01; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.app.Activity; import android.content.pm.ApplicationInfo; import android.graphics.Bitmap; import android.graphics.BitmapFactory; public class GetResImageActivity extends Activity { Button button;//獲取圖片資源btn ImageView imageview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_get_res_image); button = (Button) findViewById(R.id.button); imageview = (ImageView) findViewById(R.id.imageview); button.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { imageview.setImageBitmap(getRes("ic_launcher")); } }); } //獲取Res下的drawable文件夾下圖片資源 private Bitmap getRes(String imageName) { ApplicationInfo appInfo = this.getApplicationInfo(); int resID = getResources().getIdentifier(imageName, "drawable", appInfo.packageName); return BitmapFactory.decodeResource(getResources(), resID); } }
xml布局如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".GetResImageActivity" > <ImageView android:id="@+id/imageview" android:background="#99CC99" android:layout_width="150dp" android:layout_height="150dp"/> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:text="獲取Res下圖片" /> </RelativeLayout>
最后效果圖:
未引用前:
點擊引用后:
完成