有一种类似苹果手机的拖动图片的控件,叫做Gallery。实现其需要用到BaseAdapter适配器来传递图片数据,简单的实现代码如下:
public class GalleryDemo extends Activity { private TextView mTextView01; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ((Gallery) findViewById(R.id.myGallery1)).setAdapter(new ImageAdapter(this)); } public class ImageAdapter extends BaseAdapter { /* 类成员 myContext为Context父类 */ private Context myContext; /* 使用android.R.drawable里的图片作为图库来源,类型为整数数组 */ private int[] myImageIds = { android.R.drawable.btn_minus, android.R.drawable.btn_radio, android.R.drawable.ic_lock_idle_low_battery, android.R.drawable.ic_menu_camera }; /* 构造器只有一个参数,即要存储的Context */ public ImageAdapter(Context c) { this.myContext = c; } /* 返回所有已定义的图片总数量 */ public int getCount() { return this.myImageIds.length; } /* 利用getItem方法,取得目前容器中图像的数组ID */ public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } /* 取得目前欲显示的图像View,传入数组ID值使之读取与成像 */ public View getView(int position, View convertView, ViewGroup parent) { /* 创建一个ImageView对象 */ ImageView i = new ImageView(this.myContext); i.setImageResource(this.myImageIds[position]); /* 设置这个ImageView对象的宽高,单位为dip */ i.setLayoutParams(new Gallery.LayoutParams(120, 120)); return i; } } }
搞定,收工!