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.aiwalls.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);
}
}
上面的就是一個最簡單的Gallery的使用,當然,有很多不足的地方,例如滑動的時候卡,不流暢。或者一下劃過幾張圖片等等,這些問題放到後面慢慢解決。
摘自 LonelyRoamer的專欄