当前位置:操作系统 > 安卓/Android >>

Android ApiDemos示例解析(119):Views->Gallery->1. Photos

Gallery 和 ListView ,Spinner (下拉框) 用一个共同点,它们都是AdapterView的子类。AdapterView的显示可以通过数据绑定来实现,数据源可以是数组或是数据库记录,数据源和AdapterView是通过Adapter作为桥梁。通过Adapter,AdatperView可以显示数据源或处理用户选取事件,如:选择列表中某项。
\

Gallery 水平显示一个列表,并且将当前选中的列表项居中显示。常用来显示一组图片。 更一般来说Adapter 的 getView 可以返回任意类型的View。(如TextView)。

本例通过扩展BaseAdapter 创建一个 ImageAdapter,用于显示一组图片,图片存放在/res/drawable 目录下,对应的资源ID如下:

[java] 
private Integer[] mImageIds = { 
 R.drawable.gallery_photo_1, 
 R.drawable.gallery_photo_2, 
 R.drawable.gallery_photo_3, 
 R.drawable.gallery_photo_4, 
 R.drawable.gallery_photo_5, 
 R.drawable.gallery_photo_6, 
 R.drawable.gallery_photo_7, 
 R.drawable.gallery_photo_8 
}; 

private Integer[] mImageIds = {
 R.drawable.gallery_photo_1,
 R.drawable.gallery_photo_2,
 R.drawable.gallery_photo_3,
 R.drawable.gallery_photo_4,
 R.drawable.gallery_photo_5,
 R.drawable.gallery_photo_6,
 R.drawable.gallery_photo_7,
 R.drawable.gallery_photo_8
};

这个Adpater的getView定义如下,返回一个ImageView:

[java]
public View getView(int position, View convertView, 
 ViewGroup parent) { 
 ImageView i = new ImageView(mContext); 
 
 i.setImageResource(mImageIds[position]); 
 i.setScaleType(ImageView.ScaleType.FIT_XY); 
 i.setLayoutParams(new Gallery.LayoutParams(136, 88)); 
 
 // The preferred Gallery item background  
 i.setBackgroundResource(mGalleryItemBackground); 
 
 return i; 

public View getView(int position, View convertView,
 ViewGroup parent) {
 ImageView i = new ImageView(mContext);

 i.setImageResource(mImageIds[position]);
 i.setScaleType(ImageView.ScaleType.FIT_XY);
 i.setLayoutParams(new Gallery.LayoutParams(136, 88));

 // The preferred Gallery item background
 i.setBackgroundResource(mGalleryItemBackground);

 return i;
}

为Gallery 设置数据源:

[java]
// Reference the Gallery view  
Gallery g = (Gallery) findViewById(R.id.gallery); 
// Set the adapter to our custom adapter (below)  
g.setAdapter(new ImageAdapter(this)); 

// Reference the Gallery view
Gallery g = (Gallery) findViewById(R.id.gallery);
// Set the adapter to our custom adapter (below)
g.setAdapter(new ImageAdapter(this));


此外,应用提供registerForContextMenu 为Gallery添加一个Context Menu,可以参见Android ApiDemos示例解析(112):Views->Expandable Lists->1. Custom Adapter

 \

 

作者:mapdigit

补充:移动开发 , Android ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,