Gallery的简单应用

Gallery是一个水平的列表选择框,它允许用户通过拖动来查看上一个、下一个列表选项。
下面是控件Gallery的额外的属性:
\


要使用一个Gallery非常的简单,只需要设置填充它内容的Adapter即可。从Adapter的体系上来看(可以看看:Android中的Adapter),显然使用BaseAdapter是最好的选择,当然SimpleAdapter也可以,不过,实现起来,没有BaseAdapter清晰和强大。所以这里的Best Practice,个人认为还是BaseAdapter。
Gallery一般是用来显示图片的,当然也经常用来显示一些自定义布局和伪3D的效果。下面,通过一个简单的例子,来解释Gallery的用法。
一、首先要定义填充Gallery的适配器,这里,选择继承BaseAdapter,自定义自己的适配器
[html]
public class GalleryAdapter extends BaseAdapter { 
    private Context context; 
    private Integer[] imagesId;//要显示的图片 
    public GalleryAdapter(Context context) { 
        this.context = context; 
        imagesId=new Integer[]{R.drawable.a,R.drawable.b,R.drawable.c,R.drawable.d}; 
    } 
 
    //返回要显示的图片的总数 
    public int getCount() { 
        return imagesId.length; 
    } 
 
    //获得相关的数据项中的指定位置的数据集。这里我们可以指定为该位置的Bitmap 
    public Object getItem(int position) { 
        Bitmap bitmap=BitmapFactory.decodeResource(context.getResources(), imagesId[position]); 
        return bitmap; 
    } 
 
    //返回相关位置的item的id,这里返回和position一样的ID 
    public long getItemId(int position) { 
        return position; 
    } 
 
    /** 
     * Get a View that displays the data at the specified position in the data set. 
     * You can either create a View manually or inflate it from an XML layout file.  
     * 得到一个在指定位置显示指定数据的视图,你可以手动的创建一个或者从XML布局文件中装载一个。 
     * 参数:position  
     * 参数:convertView 如果可以的话,旧的视图可以被重用,不过用之前要检测它是否为null 
     * 参数:parent 这个视图最后要依附的父视图 www.2cto.com  
     */ 
    public View getView(int position, View convertView, ViewGroup parent) { 
        ImageView imageView=new ImageView(context); 
        Bitmap bitmap=BitmapFactory.decodeResource(context.getResources(), imagesId[position]); 
        imageView.setImageBitmap(bitmap); 
        return imageView; 
    } 
     

二、选择我们的Gallery,这里使用系统的Gallery,当然,为了某些特殊的效果,也可以选择自定义自己的Gallery
三、现在布局文件中定义我们的Gallery,然后在Activity中使用
[html]
<Gallery  
    android:id="@+id/gallery" 
    android:spacing="100dp" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"/> 

[html]
public class ImageScanActivity extends Activity { 
 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
        Gallery gallery=(Gallery)findViewById(R.id.gallery); 
        GalleryAdapter adapter=new GalleryAdapter(this); 
        gallery.setAdapter(adapter); 
    } 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值