Android 对Gallery的挖掘

  一.循环Gallery

现在看一下官方API的文档,可以看到这样一句话:该类已被弃用,其他水平滚动窗口小部件包括HorizontalScrollView和ViewPager从支持库。因为这个类是API Level 1里面的,时间比较久了。虽说被弃用,也只是不再支持后续的更新,但是我们也可以用它来作为一个学习的例子。所以说即使是Gallery不让用了,我们还可以使用HorizontalScrollView和ViewPager呢。ViewPager已经说过了,今天的主角是Gallery。

  Gallery是用来水平滚动的显示一系列项目Gallery组件可以横向显示一个图像列表,当单击当前图像的后一个图像时,这个图像列表会向左移动一格,当单击当前图像的前一个图像时,这个图像列表会向右移动一样。也可以通过拖动的方式来向左和向右移动图像列表在使用Gallery的时候,我们应指定他的背景,不然它的项目会紧凑的贴在一起,不会产生画廊的效果了。但是,你也可以通过指定Gallery的属性来设置距离,高度等参数来产生画廊的效果。显然这样做比较麻烦,除非自定义一些其他效果。

   最简单的情况是,我们在一个xml布局中添加一个Gallery,如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <Gallery 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/gallery"
        />
</RelativeLayout>
  Gallery有几个xml属性:

  animationDuration当布局已经改变,设置一个过渡动画应该运行多长时间(以毫秒为单位)。

  gravity:项目的位置

  spacing设置项目之间间距

  unselectedAlpha:设置没有选择时的Alpha

  另外Gallery还有一个内部类,Gallery.LayoutParams,继承自LayoutParams,用来提供一个位置来保存当前转换信息和之前的位置转换信息。

  定义完xml文件,之后就是在是在Activity里面实例化Gallery,设置Adapter,看代码

package com.example.androidgallerydemo;

import com.example.galleryFlowdemo.DGalleryActivity;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.res.TypedArray;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;

public class AndroidGalleryDemo extends Activity {

	private Intent intent;
	private Gallery gallery;
	private ImageView imageView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_android_gallery_demo);
        
        gallery=(Gallery) findViewById(R.id.gallery);
        TypedArray typedArray = obtainStyledAttributes(R.styleable.Gallery);  //设置背景风格。Gallery背景风格定义在attrs.xml中  
        MyImageAdapter adapter=new MyImageAdapter(this);
        adapter.setmGalleryItemBackground(typedArray.getResourceId(R.styleable.Gallery_android_galleryItemBackground, 0));  //设置gallery背景
        gallery.setAdapter(adapter);  
        gallery.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Toast.makeText(AndroidGalleryDemo.this, "" + arg2, Toast.LENGTH_SHORT).show();
				switch(arg2){
				case 0:
					intent=new Intent(AndroidGalleryDemo.this,DGalleryActivity.class);
					startActivity(intent);
				}
			}
        	
		});
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_android_gallery_demo, menu);
        return true;
    }
}
  这里我们需要自己定义一个Adapter,继承自BaseAdapter,BaseAdapter是一个非常重要的类,大家一定要熟练掌握如何继承各种形式的BaseAdapter。代码如下:

package com.example.androidgallerydemo;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;

/*
 *  MyImageAdapter 用来控制gallery的资源和操作.
 */
public class MyImageAdapter extends BaseAdapter {

	private int mGalleryItemBackground;// 用来设置gallery的风格
	
	public int getmGalleryItemBackground() {
		return mGalleryItemBackground;
	}

	public void setmGalleryItemBackground(int mGalleryItemBackground) {
		this.mGalleryItemBackground = mGalleryItemBackground;
	}

	private Context context;
	private Integer[] imageids={R.drawable.a,R.drawable.b,R.drawable.c,R.drawable.d};//图片的资源ID,我们在gallery浏览的图片  
	
	public MyImageAdapter(Context context){//构造函数  
		this.context=context;
	}
	
	public int getCount() {//返回所有图片的个数  		
		return imageids.length;
	}

	public Object getItem(int arg0) { //返回图片在资源的位置  		
		return arg0;
	}

	public long getItemId(int position) {//返回图片在资源的位置  		
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {  //此方法是最主要的,他设置好的ImageView对象返回给Gallery  
		ImageView imageview = new ImageView(context); 
		imageview.setImageResource(imageids[position]);  //通过索引获得图片并设置给ImageView  
		imageview.setScaleType(ImageView.ScaleType.FIT_XY); //设置ImageView的伸缩规格,用了自带的属性值
		imageview.setLayoutParams(new Gallery.LayoutParams(128, 128));//设置布局参数  
		imageview.setBackgroundResource(mGalleryItemBackground); //设置风格,此风格的配置是在xml中  
		return imageview;
	}
}
  还有就是背景的样式,ImageAdapter类的构造方法中获得了Gallery组件的属性信息。这些信息被定义在res\values\attrs.xml文件中,代码如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="Gallery">
        <attr name="android:galleryItemBackground" />
    </declare-styleable>
</resources>
它就是来产生那个方框的效果的, 这样就完成了最简单的gallery的使用,效果如下:

 

   二.循环Gallery

下面对这个例子做一下拓展,常规做法,Gallery组件只能有限地显示指定的图像。也就是说,如果为Gallery组件指定了4张图像,那么当Gallery组件显示到第4张时,就不会再继续显示了。这虽然在大多数时候没有什么关系,但在某些情况下,我们希望图像显示到最后一张时再重第1张开始显示,也就是循环显示。要实现这种风格的Gallery组件,就需要对GalleryAdapter对象进行一番修改。本来想在Api提供的方法中寻找突破口,但是却未果,可能还是自己水平不行,所以只能借鉴一下网上的一个解决方法。

  ImageAdapter类中有两个非常重要的方法:getCountgetView。其中getCount方法用于返回图像总数,要注意的是,这个总数不能大于图像的实际数(可以小于图像的实际数),否则会抛出越界异常。当Gallery组件要显示某一个图像时,就会调用getView方法,并将当前的图像索引(position参数)传入该方法。一般getView方法用于返回每一个显示图像的组件(ImageView对象)。从这一点可以看出,Gallery组件是即时显示图像的,而不是一下将所有的图像都显示出来。在getView方法中除了创建了ImageView对象,还用从resIds数组中获得了相应的图像资源ID来设置在ImageView中显示的图像。最后还设置了Gallery组件的背景显示风格。所以position的数值和getCount是对应的,比如我们这里是四个图片,那么position就是从0到3.如果我们想要实现循环那么当position的数值超过3时就应该让它变为0,解决方法就是取余,用position来除图片数组的长度,公式是:imageids=[position%imageids.length]。这样,当position超过3时,它的值是4,而图片数组长度也是4,求余就是0,这样gallery就会显示数组里第一个图片,同理当position为5,求余为1,显示第二个图片,以此类推。

   这样,只要在之前的MyImageAdapter修改一下即可,一个是getCount返回值为:

 public int getCount()
        {
            return Integer.MAX_VALUE;
        }
    一个是设置图片显示资源为:  imageView.setImageResource(resIds[position  %  resIds.length]);

  当然,这种方法从本质上说只是伪循环,也就是说,如果真把图像移动到getCount方法返回的值那里,那也就显示到最后一个图像的。不过在这里getCount方法返回的是Integer.MAX_VALUE,这个值超过了20亿,除非有人真想把图像移动到第20亿的位置,否则Gallery组件看着就是一个循环显示图像的组件。 

   三.菜单Gallery

  而且,gallery有很多的方法供我们使用,比如选中一个项目,项目移动,keyDown,keyUp等等。在这里我们是展示了一系列图片,也可以用gallery来当TabWidget作为菜单项。

   这个比较简单了,在gallery的OnClickListener()方法里加载各个页面的布局文件就可以了。有人这么做来替换TabWidget,因为后者比较浪费资源,前者是只有在用时才会加载。

    四.Gallery3D效果

   先看一下效果图,


  那如何实现呢,这个就需要用到关于图像处理方面的类了。

  1.倒影效果的实现:

第一:利用Matrix矩阵来实现图片的旋转。

第二:利用旋转后的图片创建一个位图reflectionImage,宽度不变,高度是原始图片的一半(自己可以随意设置),就是效果图中倒影的大小

第三:创建一个能包含原始图片和倒影图片的位图finalReflection(宽度一样,高度是原始图片的高度加上倒影图片的高度)

第四:用刚创建的位图finalReflection创建一个画布

第五:把原始图片和倒影图片添加到画布上去

第六:创建线性渐变LinearGradient对象,实现倒影图片所在的区域是渐变效果


这个写在MyImageAdapter里面就可以了,代码如下:

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Bitmap.Config;
import android.graphics.PorterDuff.Mode;
import android.graphics.Shader.TileMode;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

public class ImageAdapter extends BaseAdapter {
	int mGalleryItemBackground;
	private Context mContext;
	private Integer[] mImageIds;
	private ImageView[] mImages;
	public ImageAdapter(Context c, Integer[] ImageIds) {
		mContext = c;
		mImageIds = ImageIds;
		mImages = new ImageView[mImageIds.length];
	}
	public boolean createReflectedImages() {
		final int reflectionGap = 4;
		int index = 0;
		for (int imageId : mImageIds) {
			Bitmap originalImage = BitmapFactory.decodeResource(mContext
					.getResources(), imageId);
			int width = originalImage.getWidth();
			int height = originalImage.getHeight();
			Matrix matrix = new Matrix();
			matrix.preScale(1, -1);
			Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0,
					height / 2, width, height / 2, matrix, false);
			Bitmap bitmapWithReflection = Bitmap.createBitmap(width,
					(height + height / 2), Config.ARGB_8888);

			Canvas canvas = new Canvas(bitmapWithReflection);
			canvas.drawBitmap(originalImage, 0, 0, null);
			Paint deafaultPaint = new Paint();
			canvas.drawRect(0, height, width, height + reflectionGap,
					deafaultPaint);

			canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);
			Paint paint = new Paint();
			LinearGradient shader = new LinearGradient(0, originalImage
					.getHeight(), 0, bitmapWithReflection.getHeight()
					+ reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.CLAMP);

			paint.setShader(shader);
			paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
			canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()
					+ reflectionGap, paint);
			ImageView imageView = new ImageView(mContext);
			imageView.setImageBitmap(bitmapWithReflection);
			imageView.setLayoutParams(new GalleryFlow.LayoutParams(180, 240));
			imageView.setScaleType(ScaleType.MATRIX);
			mImages[index++] = imageView;
		}
		return true;
	}
	private Resources getResources() {
		// TODO Auto-generated method stub
		return null;
	}
	public int getCount() {
		return mImageIds.length;
	}
	public Object getItem(int position) {
		return position;
	}
	public long getItemId(int position) {
		return position;
	}
	public View getView(int position, View convertView, ViewGroup parent) {
		return mImages[position];
	}
        public float getScale(boolean focused, int offset) {
		return Math.max(0, 1.0f / (float) Math.pow(2, Math.abs(offset)));
	}

}
这样就实现倒影效果了,那如何在gallery中显示呢,我们还需要重写Gallery,才会显示如上的效果,如果不重写而是直接运行的话不仅没有效果还会报错。重写的目的就是实现像上面那样,图片有间距等效果,代码如下:

import android.content.Context;
import android.graphics.Camera;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Transformation;
import android.widget.Gallery;
import android.widget.ImageView;

public class GalleryFlow extends Gallery {

    private Camera mCamera = new Camera();
    private int mMaxRotationAngle = 60;
    private int mMaxZoom = -120;
    private int mCoveflowCenter;
	public GalleryFlow(Context context) {
            super(context);
            this.setStaticTransformationsEnabled(true);
    }
	public GalleryFlow(Context context, AttributeSet attrs) {
            super(context, attrs);
            this.setStaticTransformationsEnabled(true);
    }
	public GalleryFlow(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            this.setStaticTransformationsEnabled(true);
    }
    public int getMaxRotationAngle() {
            return mMaxRotationAngle;
    }
    public void setMaxRotationAngle(int maxRotationAngle) {
            mMaxRotationAngle = maxRotationAngle;
    }
    public int getMaxZoom() {
            return mMaxZoom;
    }
    public void setMaxZoom(int maxZoom) {
            mMaxZoom = maxZoom;
    }
    private int getCenterOfCoverflow() {
            return (getWidth() - getPaddingLeft() - getPaddingRight()) / 2
                            + getPaddingLeft();
    }
    private static int getCenterOfView(View view) {
            return view.getLeft() + view.getWidth() / 2;
    }
    protected boolean getChildStaticTransformation(View child, Transformation t) {
            final int childCenter = getCenterOfView(child);
            final int childWidth = child.getWidth();
            int rotationAngle = 0;
            t.clear();
            t.setTransformationType(Transformation.TYPE_MATRIX);
            if (childCenter == mCoveflowCenter) {
                    transformImageBitmap((ImageView) child, t, 0);
            } else {
                    rotationAngle = (int) (((float) (mCoveflowCenter - childCenter) / childWidth) * mMaxRotationAngle);
                    if (Math.abs(rotationAngle) > mMaxRotationAngle) {
                            rotationAngle = (rotationAngle < 0) ? -mMaxRotationAngle
                                            : mMaxRotationAngle;
                    }
                    transformImageBitmap((ImageView) child, t, rotationAngle);
            }
            return true;
    }
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
            mCoveflowCenter = getCenterOfCoverflow();
            super.onSizeChanged(w, h, oldw, oldh);
    }
    private void transformImageBitmap(ImageView child, Transformation t,
                    int rotationAngle) {
            mCamera.save();
            final Matrix imageMatrix = t.getMatrix();
            final int imageHeight = child.getLayoutParams().height;
            final int imageWidth = child.getLayoutParams().width;
            final int rotation = Math.abs(rotationAngle);
            // 在Z轴上正向移动camera的视角,实际效果为放大图片。
            // 如果在Y轴上移动,则图片上下移动;X轴上对应图片左右移动。
            mCamera.translate(0.0f, 0.0f, 100.0f);
            // As the angle of the view gets less, zoom in
            if (rotation < mMaxRotationAngle) {
                    float zoomAmount = (float) (mMaxZoom + (rotation * 1.5));
                    mCamera.translate(0.0f, 0.0f, zoomAmount);
            }
            // 在Y轴上旋转,对应图片竖向向里翻转。
            // 如果在X轴上旋转,则对应图片横向向里翻转。
            mCamera.rotateY(rotationAngle);
            mCamera.getMatrix(imageMatrix);
            imageMatrix.preTranslate(-(imageWidth / 2), -(imageHeight / 2));
            imageMatrix.postTranslate((imageWidth / 2), (imageHeight / 2));
            mCamera.restore();
    }
}

至此就完成了3D效果显示,其实Gallery还有很多其他的可以实现的效果。大家只要有想法就去实现吧!

 五.点击放大效果
     点击放大效果就是选种的item被放大,而没有选中的则正常显示。代码如下:

package com.example.gallery;

import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;

public class MainActivity extends Activity {
	
	public Gallery gallery = null;
	public GalleryAdapter adapter = null;//Gallery的适配器
	public ImageView img = null;
	public int selectNum = 0;//全局变量,保存被选中的item

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		gallery = (Gallery) findViewById(R.id.gallery);
		// 图片
		final List<Drawable> list = new ArrayList<Drawable>();
		list.add(getResources().getDrawable(R.drawable.jy));
		list.add(getResources().getDrawable(R.drawable.jy));
		list.add(getResources().getDrawable(R.drawable.jy));
		list.add(getResources().getDrawable(R.drawable.jy));
		list.add(getResources().getDrawable(R.drawable.jy));
		list.add(getResources().getDrawable(R.drawable.jy));
		list.add(getResources().getDrawable(R.drawable.jy));
		list.add(getResources().getDrawable(R.drawable.jy));
		adapter = new GalleryAdapter(this, list);

		gallery.setAdapter(adapter);
		gallery.setSelection((int) (list.size() / 2));// 设置默认显示的图片
		gallery.setOnItemSelectedListener(new Gallery.OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				System.out.println(arg2);
				selectNum = arg2;//
				adapter.notifyDataSetChanged();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				System.out.println("not");
			}
		});

		gallery.setOnItemClickListener(new Gallery.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
			}
		});

	}

	public class GalleryAdapter extends BaseAdapter {
		public List<Drawable> list = null;
		public Context ctx = null;

		public GalleryAdapter(Context ctx, List<Drawable> list) {
			this.list = list;
			this.ctx = ctx;
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			img = new ImageView(ctx);
			img.setImageDrawable(list.get(position));
			if (selectNum == position) {
				img.setLayoutParams(new Gallery.LayoutParams(200, 200));//如果被选择则放大显示
			} else {
				img.setLayoutParams(new Gallery.LayoutParams(100, 100));//否则正常
			}
			return img;
		}

	}

}
xml布局,

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center_horizontal"
    android:background="#532342"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <Gallery
        android:id="@+id/gallery"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</LinearLayout>
效果如下:

                              


评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值