Android高级组件Gallery画廊视图使用方法详解

  package com.example.test;

  import android.app.Activity;

  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 MainActivity extends Activity{

  @Override

  protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.main);

  Gallery gallery=(Gallery)findViewById(R.id.gallery1);

  final int [] imageId=new int[]{R.drawable.img01,R.drawable.img02,R.drawable.img03,R.drawable.img04,

  R.drawable.img05,R.drawable.img06,R.drawable.img07,R.drawable.img08,

  R.drawable.img_top,R.drawable.ic_launcher,R.drawable.in,R.drawable.stop,};//定义并初始化保存图片id的数组

  //创建并改写BaseAdapter适配器

  BaseAdapter adapter=new BaseAdapter(){

  @Override

  public View getView(int position, View convertView, ViewGroup parent) {

  ImageView imageView;//声明一个ImageView的对象

  if(convertView==null){

  imageView=new ImageView(MainActivity.this);//实例化ImageView对象

  imageView.setScaleType(ImageView.ScaleType.FIT_XY);//设置缩放方式

  imageView. setLayoutParams(new Gallery.LayoutParams(180, 135));//设置ImageView宽高

  TypedArray typedArray=obtainStyledAttributes(R.styleable.Gallery);//获取自定义属性对象

  //为imageView设置背景图片的资源,使用了自定义属性对象typedArray获取自定义背景资源值

  imageView.setBackgroundResource(

  typedArray.getResourceId(R.styleable.Gallery_android_galleryItemBackground, 0));

  imageView.setPadding(5, 0, 5, 0);//设置内边距

  }else{

  //如果以前new过View就使用convertView的缓存

  imageView=(ImageView)convertView;

  }

  imageView.setImageResource(imageId[position]);

  return imageView;

  }

  //功能:获得当前选项的id

  @Override

  public long getItemId(int position) {

  return position;

  }

  //功能:获得当前选项

  @Override

  public Object getItem(int position) {

  return position;

  }

  //获得数量

  @Override

  public int getCount() {

  return imageId.length;

  }

  };

  gallery.setAdapter(adapter);

  gallery.setSelection(imageId.length/2);

  gallery.setOnItemClickListener(new OnItemClickListener() {

  @Override

  public void onItemClick(AdapterView<?> parent, View v, int position,

  long id) {

  Toast.makeText(MainActivity.this, "您选择了第"+String.valueOf(position)+"张图片",

  Toast.LENGTH_SHORT).show();

  }

  });

  }

  }