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

前言

通过官方案例学习,是最直接的方法。结合书本在此介绍一下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了。

源码下载

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值