package xiaosi.gallery;
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.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
public class GalleryActivity extends Activity {
/** Called when the activity is first created. */
private Gallery gallery =null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gallery = (Gallery)findViewById(R.id.gallery);
//设置图片适配器
gallery.setAdapter(new ImageAdapter(this));
gallery.setSpacing(5);
//设置监听器
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(GalleryActivity.this, "点击了第"+arg2+"张图片", Toast.LENGTH_LONG).show();
}
});
}
}
class ImageAdapter extends BaseAdapter{
int mGalleryItemBackground;
private Context context;
//图片源数组
private Integer[] imageInteger={
R.drawable.a,
R.drawable.b,
R.drawable.c,
R.drawable.d
};
public ImageAdapter(Context c){
context = c;
TypedArray attr = context.obtainStyledAttributes(R.styleable.HelloGallery);
mGalleryItemBackground = attr.getResourceId(R.styleable.HelloGallery_android_galleryItemBackground, 0);
attr.recycle();
}
// 获取图片的个数
public int getCount() {
return imageInteger.length;
}
// 获取图片在库中的位置
public Object getItem(int position) {
return position;
}
// 获取图片ID
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(context);
// 给ImageView设置资源
imageView.setImageResource(imageInteger[position]);
// 设置显示比例类型
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
// 设置布局 图片120*80
imageView.setLayoutParams(new Gallery.LayoutParams(180, 100));
imageView.setBackgroundResource(mGalleryItemBackground);
return imageView;
}
}
mian.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Gallery
android:id="@+id/gallery"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="bottom"
android:background="?android:galleryItemBackground"/>
</LinearLayout>
创建一个新的XML文件在res/values/目录下
attrs.xml命名。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="HelloGallery">
<attr name="android:galleryItemBackground" />
</declare-styleable>
</resources>
这是一个定制的styleable资源,可以应用于一个布局。