我们有时候在iPhone手机上或者Windows上面看到动态的图片,可以通过鼠标或者手指触摸来移动它,产生动态的图片滚动效果,还可以根据你的点击或者触摸触发其他事件响应。同样的,在Android中也提供这这种实现,这就是通过Gallery在UI上实现缩略图浏览器。
我们来看看Gallery是如何来实现的,先把控件从布局文件中声明,只需知道ID为gallery。
1 | |
一般情况下,我们在Android中要用到类似这种图片容器的控件,都需要为它指定一个适配器,让它可以把内容按照我们定义的方式来显示,因此我们来给它加一个适配器,至于这个适配器如何实现,后面接着来操作,这里只需知道这个适配器的类叫
1 | |
复制代码接下来就是重头戏了,适配器可以说是最重要的,我们来看看如何做?到这里似乎还缺少一些很重要的东西?什么东西呢?我们需要显示的是图片,那么图片我们当然首先要准备好,这里我们准备了5张图片(存放drawable文件夹中),我们用其IDs做索引,以便在适配器中使用。
1 2 3 4 5 6 7 | |
OK,这里将开始定义适配器了,通过继承BaseAdapter用以实现的适配器。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
|
至此,整个Gallery基本都是先完成了,我们还需要为它添加一个监听器,否则这个缩略图浏览器就仅仅只可以看不能用了。
1 2 3 4 5 6 7 8 9 10 |
|
一、效果图展示
最近下载几款手机应用研究了下,发了有些自定义控件惊人的相似,所以我觉得在以后的开发中,对一些控件的复用肯定是很多的,在首页(非载入页)一般都会有一个幻灯片效果,既可以放广告也可以放推荐,如果图片设计的好看,效果一般都会不错,既然用到了Gallery,也附带把相框效果的例子写一写(淘宝详情界面的商品图片滑动展示)
(1)幻灯片效果展示:
(2)商品图片滑动展示
查看大图:
二、部分代码说明
1、幻灯片效果的实现:
自定义Gallery:DetailGallery.java
可视界面:ImgSwitchActivity.java
适配类:GalleryIndexAdapter.java
自定义Gallery主要重写onFling通过按下和松手的位置不同比较是向右移动还是向左移动,部分代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
2、在适配类 GalleryIndexAdapter主要完成幻灯片的循环播放,在getCount里面返回值返回Integer.MAX_VALUE,然后在getView里面根据position与传进来初始图片个数进行余数计算得到每次循环到哪张图片。部分代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
3、在可视界面里面实现逻辑控制,通过定时器定时刷新幻灯片,定时器通过定时发送消息,消息接受处理机制接收到消息之后,就模拟滑动事件,调用Gallery的onFling方法实现图片自动切换效果。选择按钮的显示效果(RadioButton)需要在Gallery的setOnItemSelectedListener进行处理。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
|
4、商品图片滑动实现过程:
图片滑动效果和上面的幻灯片效果非常的类似,只是在逻辑处理和界面上有一些小小的区别。
(1)适配器类GalleryAdapter.java上面进行了图片缩放处理,节省了内存开销,又可把图片按照自己的要求缩放。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
|
(2)添加了一个相框效果,如果图片加载失败,就会出现一个图片压缩之后大小相等的相框图片。
1 2 3 4 5 6 7 8 | |
三、开发中遇到一些问题1、
1 | |
如果需要把当前子childview添加到另外一个view里面去,则必须在当前的父View里面移除掉当前的childView,如果不进行这样处理则会抛出Caused by: java.lang.IllegalStateException异常,提示The specified child already has a parent. You must call removeView() on the child's parent first.
2、在进行图片缩放的时候,记得处理好dp和px直接的转换。