Android使用图片资源

android项目下资源文件放到res文件夹下面,工程会在gen/com/clj/img/R.java中对资源自动统一管理。资源文件会有多套,针对不同的屏幕分辨率,多套分辨率的资源文件分别放drawable-hdpi、drawable-ldpi、drawable-mdpi、drawable-xhdpi、drawable-xxhdpi。

Android使用图片资源_第1张图片

可以有2种方式使用资源文件,一种是在res/layout/fragment_main.xml这个布局文件中使用控件,另一种是在后台java代码中使用。首先我们将下面这个图片文件复制到drawable-hdpi目录下。

一、在布局文件中使用资源文件

1、点击fragment_main.xml进入布局视图

Android使用图片资源_第2张图片

2、下图就是界面布局视图,拖一个ImageView控件到界面上。

Android使用图片资源_第3张图片

3、拖控件到界面的过程中会出现如下图的图形选择界面,选择我们放到资源文件夹的icon图片文件。确定后,就在界面上添加了ImageView图片控件,并且控件里面放了一张图片。

Android使用图片资源_第4张图片

在res/layout/fragment_main.xml中会多生成如下这段代码,这个就是图片控件。

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_marginLeft="50dp"
        android:layout_marginTop="47dp"
        android:layout_toRightOf="@+id/textView1"
        android:src="@drawable/icon" />
运行程序,在AVD中便可以看到添加的图片了。

Android使用图片资源_第5张图片

二、java代码中使用资源文件

1、修改src/com/clj/img/MainActivity.java的onCreate方法。

@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		//创建ImageView对象
		ImageView iv=new ImageView(this);
		//为ImageView进行设置,把图片设置给对象
		iv.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon));
		//将ImageView设置给当前view
		this.setContentView(iv);

	}

2、运行程序,在AVD中看到如下图的效果。

Android使用图片资源_第6张图片


你可能感兴趣的:(android)