Android--Gallery与ImageSwitcher制作图片浏览器

一、Gallery的使用

(Gallery是过期控件,以后不建议使用,可用HorizontalScrollView、ImageView代替)

1. 在布局xml文件中添加Gallery标签

<Gallery
  android:id="@+id/gallery"
  ....
/>

2.准备数据源

<span style="font-size:18px;">int[] res={R.drawable.item1,R.drawable.item2,...};</span>

3.可以自定义一个数据适配器如ImageAdapter (继承BaseAdapter)

(1)BaseAdapter中的重要方法  

public int getCount()//返回已定义的数据源的总数量
{
  return res.length;  //Gallery循环滚动功能时,改为 return Integer.MAX_VALUE;
}
public Object getItem(int position)//取得当前容器中的对象
public long getItemId(int position)//取得当前容器中的数据ID,即数组下标的值
public View getView(int position, View convertView, ViewGroup parent)//取得目前欲显示的图像View,传入数组ID值使之读取与成像。根据数据源的个数,会调用相应次数的getView方法
{
  ImageView image=new ImageView(context);
  image.setBackGroundResource(res[position]);//Gallery循环滚动功能时,改为res[position%res.length];
  image.setLayoutParams(new Gallery.LayoutParams(200,150));//图片在Gallery中的大小
  image.setScaleType(ScaleType.FIT_XY);//横向纵向的拉伸到200*150
  return image;
}


 
 

 
ImageAdapter需要一个构造函数 

ImageAdapter(int[] res, Context context)

4.加载适配器

adapter=new ImageAdapter(res,this);

gallery.setAdapter(adapter);

5. Gallery的监听器OnItemSelectedListener

gallery加载监听器  gallery.setOnItemSelectedListener(this);

监听器包含两个函数 onItemSelected (传入当前选中的图片,及其位置position)和 onNothingSelected

二、ImageSwitcher的使用(与ImageView功能类似,但是效果更炫,可指定图片切换时的动画效果)

1.在布局xml文件中添加ImageSwitcher标签

<ImageSwitcher
  android:id="@+id/is"
  ......></ImageSwitcher>

2. 为了让ImageSwitcher对象 is加载图片,需让is所在的当前类实现接口 ViewFactory,重写其View makeView()方法

public View makeView(){
  ImageView image=new ImageView(this);
  image.setScaleType(ScaleType.FIT_CENTER);//等比例缩放,保持图片居中
  return image;
}

3. ImageSwitcher加载图片资源(实验中在Gallery监听事件方法onItemSelected中实现)

  is.setBackgroundResource(res[position%res.length]);

4. ImageSwitcher对象加载Factory  —— is.setFactory(this);

5. ImageSwitcher设置动画效果

is.setInAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_in);//淡入
is.setOutAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_out);//淡出




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值