展会信息港展会大全

Android ApiDemos示例解析(119):Views->Gallery->1. Photos
来源:互联网   发布日期:2015-10-03 10:44:56   浏览:1128次  

导读:Gallery 和 ListView ,Spinner (下拉框) 用一个共同点,它们都是AdapterView的子类。AdapterView的显示可以通过数据绑定来实现,数据源可以是数组或是...

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开发 教程

AiLab云推荐
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港