第一步:设计xml布局文件
代码如下:main.xm
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
android:id="@+id/myGallery"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:spacing="3px"
android:text="@string/hello" />
第二步:自定义一个适配器,这个适配器继承BaseAdapter这个类
代码如下:
package net.loonggg.gallery;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
public class ImageGalleryAdapter extends BaseAdapter
{
private Context context;
// 里面所有的方法表示的是可以根据指定的显示图片的数量,进行每个图片的处理
private int[] image = new int[] { R.drawable.ispic_a,
R.drawable.ispic_b,
R.drawable.ispic_c, R.drawable.ispic_d, R.drawable.ispic_e
};
public ImageGalleryAdapter(Context context) {
this.context = context;
}
public int getCount() { // 取得要显示内容的数量
return image.length;
}
public Object getItem(int position) { //
每个资源的位置
return image[position];
}
public long getItemId(int position) { //
取得每个项的ID
return image[position];
}
// 将资源设置到一个组件之中,很明显这个组件是ImageView
public View getView(int position, View convertView,
ViewGroup parent) {
ImageView iv = new ImageView(context);
iv.setBackgroundColor(0xFFFFFFFF);
iv.setImageResource(image[position]);//
给ImageView设置资源
iv.setScaleType(ImageView.ScaleType.CENTER);//
设置对齐方式
iv.setLayoutParams(new
Gallery.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
return iv;
}
}
第三步:主方法:
package net.loonggg.gallery;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import
android.widget.AdapterView.OnItemClickListener;
import android.widget.Gallery;
import android.widget.Toast;
public class GalleryActivity extends Activity {
private Gallery myGallery;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myGallery = (Gallery)
findViewById(R.id.myGallery);
myGallery.setAdapter(new
ImageGalleryAdapter(this));
myGallery.setOnItemClickListener(new
OnItemClickListenerImpl());
}
private class OnItemClickListenerImpl implements
OnItemClickListener {
public void onItemClick(AdapterView