Hello, Views(一)Gallery滑动的图片(附源码下载)

(本文根据官方tutorials翻译而来)

前言

通过官方案例学习,是最直接的方法。结合书本在此介绍一下gallery的运用。

效果

涉及到的类

· BaseAdapter

· Gallery

· ImageView

· AdapterView.OnItemClickListener

下面是工程的结构,

 

新建:1)一个主activity命名为HelloGalleryActivity.java,

2)一个自定义adapter命名为GalleryAdapter用于填充Gallery

3) 在drawable里面放置使用到的图片资源

4)在values里面新建一个xmlatrrs.xml用于定义图片的边框效果

5)在mian.xml里面添加一个gallery

代码书写:

HelloGalleryActivity里面重写的onCreate()方法添加以下代码:

public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Gallery gallery = (Gallery) findViewById(R.id.gallery1);
gallery.setAdapter(new GalleryAdapter(this));
//下面的单击监听用于显示一个toast,作用是显示所单击的图片的下标
gallery.setOnItemClickListener(new OnItemClickListener()
{
           @Override
           public void onItemClick(AdapterView parent, View v, int position, long id)
              {
               Toast.makeText(HelloGalleryActivity.this, "" + position, Toast.LENGTH_SHORT).show();
              }
       });
}

GalleryAdapter里面,自动生成了一些需要重写的方法:

public class GalleryAdapter extends BaseAdapter
{
  //用于图片的背景边框
   int mGalleryItemBackground;
  //获得上下文的引用
   private Context mContext;
  //存放图片资源的整型数组
   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 GalleryAdapter(Context c)
   {
     mContext = c;
     // 设置边框样式
     TypedArray a = c.obtainStyledAttributes(R.styleable.HelloGallery);
     mGalleryItemBackground = a.getResourceId(
     R.styleable.HelloGallery_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.setLayoutParams(new Gallery.LayoutParams(150, 100));
     i.setScaleType(ImageView.ScaleType.FIT_XY);
     i.setBackgroundResource(mGalleryItemBackground);

     return i;
   }

}

完善atrrs.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <declare-styleable name="HelloGallery">
  <attr name="android:galleryItemBackground" />
  </declare-styleable>
</resources>

基本上这样就OK了。

源码下载

 

posted @ 2012-02-19 13:52  小文字  阅读(1733)  评论(0编辑  收藏  举报