android 显示int组件,可循环显示图像的Android Gallery组件

372990c5008d59c9a355ac15d72d7759.png

类型:源码相关大小:23.6M语言:中文 评分:9.1

标签:

立即下载

第 2 页 这些图像的资源ID都保存在int数组中

下面将这些图像的资源ID都保存在int数组中,代码如下:

代码

private int[] resIds = new int[]

{ R.drawable.item1, R.drawable.item2, R.drawable.item3,

R.drawable.item4, R.drawable.item5, R.drawable.item6,

R.drawable.item7, R.drawable.item8, R.drawable.item9,

R.drawable.item10, R.drawable.item11, R.drawable.item12,

R.drawable.item13, R.drawable.item14, R.drawable.item15 };

在本例的main.xml文件中配置了一个Gallery组件,代码如下:

代码

android:orientation="vertical" android:layout_width="fill_parent"

android:layout_height="fill_parent">

android:layout_height="wrap_content" android:layout_marginTop="30dp" />

现在在onCreate方法中装载这个组件,代码如下:

代码

public void onCreate(Bundle savedInstanceState)

{

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

// 装载Gallery组件

Gallery gallery = (Gallery) findViewById(R.id.gallery);

// 创建用于描述图像数据的ImageAdapter对象

ImageAdapter imageAdapter = new ImageAdapter(this);

// 设置Gallery组件的Adapter对象

gallery.setAdapter(imageAdapter);

}

在上面的代码中涉及到一个非常重要的类:ImageAdapter。该类是android.widget.BaseAdapter的子类,用于描述图像信息。下面先看一下这个类的完整代码。

代码

public class ImageAdapter extends BaseAdapter

{

int mGalleryItemBackground;

private Context mContext;

public ImageAdapter(Context context)

{

mContext = context;

// 获得Gallery组件的属性

TypedArray typedArray = obtainStyledAttributes(R.styleable.Gallery);

mGalleryItemBackground = typedArray.getResourceId(

R.styleable.Gallery_android_galleryItemBackground, 0);

}

// 返回图像总数

public int getCount()

{

return resIds.length;

}

public Object getItem(int position)

{

return position;

}

public long getItemId(int position)

{

return position;

}

// 返回具体位置的ImageView对象

public View getView(int position, View convertView, ViewGroup parent)

{

ImageView imageView = new ImageView(mContext);

// 设置当前图像的图像(position为当前图像列表的位置)

imageView.setImageResource(resIds[position]);

imageView.setScaleType(ImageView.ScaleType.FIT_XY);

imageView.setLayoutParams(new Gallery.LayoutParams(163, 106));

// 设置Gallery组件的背景风格

imageView.setBackgroundResource(mGalleryItemBackground);

return imageView;

}

}

在编写ImageAdapter类时应注意的两点:

1. 在ImageAdapter类的构造方法中获得了Gallery组件的属性信息。这些信息被定义在res\values\attrs.xml文件中,代码如下:

上面的属性信息用于设置Gallery的背景风格。

2. 在ImageAdapter类中有两个非常重要的方法:getCount和getView。其中getCount方法用于返回图像总数,要注意的是,这个总数不能大于图像的实际数(可以小于图像的实际数),否则会抛出越界异常。当Gallery组件要显示某一个图像时,就会调用getView方法,并将当前的图像索引(position参数)传入该方法。一般getView方法用于返回每一个显示图像的组件(ImageView对象)。从这一点可以看出,Gallery组件是即时显示图像的,而不是一下将所有的图像都显示出来。在getView方法中除了创建了ImageView对象,还用从resIds数组中获得了相应的图像资源ID来设置在ImageView中显示的图像。最后还设置了Gallery组件的背景显示风格。

OK,现在来运行这个程序,来回拖动图像列表,就会看到如图1和图2所示的效果了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值