在iphone手机上用手指拖动图片移动,这功能很Cool,咱Android也不能含糊,用Gallery类就可以实现这个功能。
今天我就做了个小小的电子相册:
假设你已经新建好了项目。
首先我们事先准备好的图片存放在drawable文件夹下,然后新建一个接口:
- public interface ImageResource {
-
- Integer[] dImageID = {
- R.drawable.sample_0,
- R.drawable.sample_1,
- R.drawable.sample_2,
- R.drawable.sample_3,
- R.drawable.sample_4,
- R.drawable.sample_5,
- R.drawable.sample_6,
- R.drawable.sample_7,
- };
- }
这个接口里有一个int型的数组保存了咱drawable下的图片,这样方便以后修改。
要用Gallery实现这个功能,先要有一个容器来存放Gallery要显示的图片,我使用的是一个继承自BaseAdapter的ImageAdapter。这个电子相册分两部分,上部分是用户可以拖动图像列表,下部分是用户选中上面图像后更大的显示出来。看图:
负责上部分显示的ImageView是imageAll,负责下部分显示的是imageOne,代码如下:
- import android.app.Activity;
- import android.content.Context;
- import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.Gallery;
public class HelloGallery extends Activity {
private ImageView imageOne;
private ImageView imageAll;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageOne = (ImageView)findViewById(R.id.imageView);
Gallery gallery = (Gallery)findViewById(R.id.gallery);
gallery.setAdapter(new ImageAdapter(this));
}
class ImageAdapter extends BaseAdapter implements ImageResource{
private int galleryItemBackground;
private Context context;
public ImageAdapter(Context context) {
this.context = context;
TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
galleryItemBackground = a.getResourceId(
R.styleable.Gallery1_android_galleryItemBackground, 0);
a.recycle();
}
public int getCount() {
return dImageID.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
imageOne.setScaleType(ImageView.ScaleType.FIT_CENTER);
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
imageAll= new ImageView(context);
imageAll.setImageResource(dImageID[position]);
imageAll.setLayoutParams(new Gallery.LayoutParams(120,120));
imageAll.setScaleType(ImageView.ScaleType.FIT_XY);
imageAll.setBackgroundResource(galleryItemBackground);
return imageAll;
}
}
} 