下面通过实例的方式来演示位图文件的使用。本实例首先在res\drawable\目录下添加两个位图文件g1.jpg和moto.jpg,并将这两个位图文件显示在Activity的ImageView中,第一个通过在布局文件中直接引用,第二个在Java代码中引用。实例步骤说明如下。
在"Chapter03_Resource"工程的res\drawable\目录下添加两张位图文件g1.jpg和moto.jpg。
创建一个布局文件test_bitmap。在该布局文件中添加两个ImageView组件用来显示图标,其中第一个ImageView组件直接引用g1.jpg文件,第二个在Java代码中进行置。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:text="测试位图资源" android:id="@+id/bitmapTextView01" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView> <ImageView android:id="@+id/bitmapImageView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/g1"></ImageView> <ImageView android:id="@+id/bitmapImageView02" android:layout_width="wrap_content" android:layout_height="wrap_content"></ImageView> </LinearLayout>
在工程的com.amaker.ch03.drawable包中创建TestBitmapActivity类。在该类顶部声明一个ImageView视图组件,在onCreate()方法中实例化该组件,并通过Resources.getDrawable()方法获得位图资源,将ImageView组件设置为可显示的图片。
import android.app.Activity; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.widget.ImageView; public class TestBitmapActivity extends Activity { // 声明ImageView对象 private ImageView myImageView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 设置当前内容布局视图 setContentView(R.layout.test_bitmap); // 通过findViewById方法获得ImageView实例 myImageView = (ImageView)findViewById(R.id.bitm- apImageView02); // 获得Resources实例 Resources r = getResources(); // 通过Resources 获得Drawable实例 Drawable d = r.getDrawable(R.drawable.moto); // 设置ImageView的ImageDrawable属性显示图片 myImageView.setImageDrawable(d); } }