Gallery的简单应用

来源:互联网 发布:淘宝购物分享在哪里 编辑:程序博客网 时间:2024/05/18 06:23

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); 
    }