首先展示一下效果图
操作步骤如下:
1)用eclipse创建Android Application"GalleryApp"。
2)修改activity_main.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/gallery1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
3)将需要的图片复制到drawable-hdpi
4)在values下面建一个叫attrs 的XML文件。
里面内容写如下
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="Gallery">
<attr name="android:galleryItemBackground" />
</declare-styleable>
</resources>
5)修改MainActivity.java代码如下
package com.example.galleryapp;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.view.*;
import android.widget.*;
public class MainActivity extends Activity {
private Gallery gallery1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gallery1 = (Gallery) findViewById(R.id.gallery1);
gallery1.setAdapter(new ImageAdapter(this));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackground;
private Context mContext;
//显示的图片集合
private Integer[] mImageIds = {
R.drawable.image1,
R.drawable.image2,
R.drawable.image3,
R.drawable.image4,
R.drawable.image5
};
public ImageAdapter(Context context) {
mContext = context;
TypedArray a = obtainStyledAttributes(R.styleable.Gallery);
mGalleryItemBackground = a.getResourceId(
R.styleable.Gallery_android_galleryItemBackground, 0);
a.recycle();
}
@Override
public int getCount() {
return mImageIds.length;
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageResource(mImageIds[position]);
i.setScaleType(ImageView.ScaleType.FIT_XY);
//设置图片的大小
i.setLayoutParams(new Gallery.LayoutParams(400, 600));
// The preferred Gallery item background
i.setBackgroundResource(mGalleryItemBackground);
return i;
}
}
}