画廊已过时,但是呢,美团还在用,我正好也要用到,所以学习下。上源码
一、前世今生:gallery和spinner都派生自AdapterView,AdapterView是ViewGroup的派生类,ViewGroup是View的派生类。
二、自我介绍:Gallery是中心锁定的,即被点击的item总是处于gallery对象的中央。
三、用法:Gallery需要适配器,适配器继承自BaseAdapter,说下getView吧:
// 将 convertView 赋给 view
ImageView view = (ImageView) convertView;
if (view == null ) // 如果 view 为空
{
view = new ImageView( ctx ); // 就新建一个
}
// 否则就是用已经存在的 convertView 。
// 上面做法可以大幅度提高程序运行性能 , 也可以减少内存的使用 , 尤其在 Gallery 对象
// 中有很多 item 的时候
// 设定显示图片
view.setImageResource( images [position]);
// 设定每个图片的显示大小
view.setLayoutParams( new Gallery.LayoutParams(48, 48));
//view.setScaleType(ImageView.ScaleType.FIT_XY); // 这个是维持图片原始大小
// 设定图片缩放:即在上面规定的大小中进行显示,并且居中
view.setScaleType(ImageView.ScaleType. CENTER_INSIDE );
return view;
设置适配器时注意:
// 设定图片之间的间隔 ( 如果无下面的语句,有时候图片会重叠 )
gallery .setSpacing(0);
摘自api:The default values for the Gallery assume you will be using Theme_galleryItemBackground as the background for each View given to the Gallery from the Adapter. If you are not doing this, you may need to adjust some Gallery properties, such as the spacing.
上述方式是设置spacing,学习下设置background:
首先在适配器的构造函数中获得gallery组件的属性信息:
TypedArray typedArray = obtainStyledAttributes(R.styleable.Gallery);
mGalleryItemBackground = typedArray.getResourceId(
R.styleable.Gallery_android_galleryItemBackground, 0);
组件的属性信息被定义在res/values/attrs.xml文件中:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="Gallery">
<attr name="android:galleryItemBackground" />
</declare-styleable>
</resources>
在getView中增加background设置:
// 设置Gallery组件的背景风格
imageView.setBackgroundResource(mGalleryItemBackground);
四、属性介绍
//设置未选中图片的透明度
gallery.setUnselectedAlpha(0.5f);
//设置选中的图片
gallery.setSelection(3);
//设置图片之间距离
gallery.setSpacing(20);