Gallery使用教程——尝试翻译一篇Android SDK Reference
Gallery使用教程
Gallery是一个布局工具,可以将其它控件组合在水平滚动条中,并且可以让当前选项的控件定位到布局的中间
在下面的教程中,你会创建一个显示照片的Gallery,并且每一个条目被选中后它会显示相应的土司消息
[list]1新建项目,取名HelloGallery.打开res/layout/main.xml文件,然后添加入以下代码
<?xml version="1.0" encoding="utf-8"?><Gallery xmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/gallery"android:layout_width="fill_parent"android:layout_height="wrap_content"/>
@Overridepublic void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Gallery gallery = (Gallery) findViewById(R.id.gallery); gallery.setAdapter(new ImageAdapter(this)); gallery.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView parent, View v, int position, long id) { Toast.makeText(HelloGallery.this, "" + position, Toast.LENGTH_SHORT).show(); } });}[/list]<?xml version="1.0" encoding="utf-8"?><resources> <declare-styleable name="HelloGallery"> <attr name="android:galleryItemBackground" /> </declare-styleable></resources>
public class ImageAdapter extends BaseAdapter { // 用来设置Galley中的每一个Item的风格,也就是ImageView的风格 int mGalleryItemBackground; private Context mContext; //图片的资源ID private Integer[] mImageIds = { 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 }; public ImageAdapter(Context c) { mContext = c; TypedArray attr = mContext.obtainStyledAttributes(R.styleable.HelloGallery); mGalleryItemBackground = attr.getResourceId( R.styleable.HelloGallery_android_galleryItemBackground, 0); attr.recycle(); } //返回所有图片的个数 public int getCount() { return mImageIds.length; } //返回图片在资源的位置 public Object getItem(int position) { return position; } //返回图片在资源的位置 public long getItemId(int position) { return position; } //此方法是最主要的,他设置好的ImageView对象返回给Gallery public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView = new ImageView(mContext); //通过索引获得图片并设置给ImageView imageView.setImageResource(mImageIds[position]); //设置布局参数 imageView.setLayoutParams(new Gallery.LayoutParams(150, 100)); //设置ImageView的伸缩规格,用了自带的属性值 imageView.setScaleType(ImageView.ScaleType.FIT_XY); //设置风格,此风格的配置是在xml中 imageView.setBackgroundResource(mGalleryItemBackground); return imageView; }}