android 拖动效果 Gallery 实例
大多数手机上都会有类似的动态效果,因为这样的动画会让人耳目一新。苹果曾经因此吸引了不少手机粉丝。那么在android上同样也可以实现此效果。
Gallery的功能就是用来显示这样的效果。简单说明一下Gallery是什么样的:
假设你放入了10个图片,那么你用Gallery的时候,用此容器来存放你的图片,在手机界面上会把图片显示出来(android的系统中带有自己的Gallery的风格)。那么你在点击后一张图片的时候前一张图片就会往前移动,而你点击的图片就会突出显示。你也可以触摸拖动图片,任意选择你想要的那张图片突出显示。
不过,通常的Gallery在你指定了10张或者更多的图片时,到了最后一张就不在循环显示了。也就是说,它只能限定显示图片。
通过一个实例来完成Gallery的用法。
首先:我们要知道Gallery是显示图片用的,那么就需要指定他的显示布局。
我们需要一个ImageView来完成此布局,而此布局需要继承BaseAdapter,来实现其中的方法来为Gallery实现效果。
我们所有要用到的图片要放在一个int型数组中,然后通过ImageView的setImageResource方法来设置需要显示的图片,然后在把此图片通过ImageView对象显示在手机屏幕上。
ImageAdapter类:
public class ImageAdapter extends BaseAdapter { // 用来设置ImageView的风格int mGalleryItemBackground;private Context context; //图片的资源IDprivate Integer[] mImageIds = {R.drawable.img1,R.drawable.img2,R.drawable.img3,R.drawable.img4,R.drawable.img5,R.drawable.img6,R.drawable.img7,R.drawable.img8}; //构造函数public ImageAdapter(Context context) {// TODO Auto-generated constructor stubthis.context = context;}//返回所有图片的个数@Overridepublic int getCount() {// TODO Auto-generated method stubreturn mImageIds.length;} //返回图片在资源的位置@Overridepublic Object getItem(int position) {// TODO Auto-generated method stubreturn position;} //返回图片在资源的位置@Overridepublic long getItemId(int position) {// TODO Auto-generated method stubreturn position;} //此方法是最主要的,他设置好的ImageView对象返回给Gallery@Overridepublic View getView(int position, View convertView, ViewGroup parent) {// TODO Auto-generated method stubImageView imageView = new ImageView(context); //通过索引获得图片并设置给ImageViewimageView.setImageResource(mImageIds[position]); //设置ImageView的伸缩规格,用了自带的属性值imageView.setScaleType(ImageView.ScaleType.FIT_CENTER); //设置布局参数imageView.setLayoutParams(new Gallery.LayoutParams(120, 120)); //设置风格,此风格的配置是在xml中imageView.setBackgroundResource(mGalleryItemBackground);return imageView;}public int getmGalleryItemBackground() {return mGalleryItemBackground;}public void setmGalleryItemBackground(int mGalleryItemBackground) {this.mGalleryItemBackground = mGalleryItemBackground;}}<?xml version="1.0" encoding="utf-8"?><resources><declare-styleable name="Gallery"><attr name="android:galleryItemBackground"/></declare-styleable></resources>
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" ><Galleryandroid:id="@+id/myGallery"android:layout_width="fill_parent"android:layout_height="wrap_content"/></LinearLayout>