Android ApiDemos示例解析(119):Views->Gallery->1. Photos

Gallery 和 ListView ,Spinner (下拉框) 用一個共同點,它們都是AdapterView的子類。AdapterView的顯示可以通過數據綁定來實現,數據源可以是數組或是數據庫記錄,數據源和AdapterView是通過Adapter作為橋梁。通過Adapter,AdatperView可以顯示數據源或處理用戶選取事件,如:選擇列表中某項。

Gallery 水平顯示一個列表,並且將當前選中的列表項居中顯示。常用來顯示一組圖片。 更一般來說Adapter 的 getView 可以返回任意類型的View。(如TextView)。

本例通過擴展BaseAdapter 創建一個 ImageAdapter,用於顯示一組圖片,圖片存放在/res/drawable 目錄下,對應的資源ID如下:

[java] 
private Integer[] mImageIds = { 
 R.drawable.gallery_photo_1, 
 R.drawable.gallery_photo_2, 
 R.drawable.gallery_photo_3, 
 R.drawable.gallery_photo_4, 
 R.drawable.gallery_photo_5, 
 R.drawable.gallery_photo_6, 
 R.drawable.gallery_photo_7, 
 R.drawable.gallery_photo_8 
}; 

private Integer[] mImageIds = {
 R.drawable.gallery_photo_1,
 R.drawable.gallery_photo_2,
 R.drawable.gallery_photo_3,
 R.drawable.gallery_photo_4,
 R.drawable.gallery_photo_5,
 R.drawable.gallery_photo_6,
 R.drawable.gallery_photo_7,
 R.drawable.gallery_photo_8
};

這個Adpater的getView定義如下,返回一個ImageView:

[java]
public View getView(int position, View convertView, 
 ViewGroup parent) { 
 ImageView i = new ImageView(mContext); 
 
 i.setImageResource(mImageIds[position]); 
 i.setScaleType(ImageView.ScaleType.FIT_XY); 
 i.setLayoutParams(new Gallery.LayoutParams(136, 88)); 
 
 // The preferred Gallery item background  
 i.setBackgroundResource(mGalleryItemBackground); 
 
 return i; 

public View getView(int position, View convertView,
 ViewGroup parent) {
 ImageView i = new ImageView(mContext);

 i.setImageResource(mImageIds[position]);
 i.setScaleType(ImageView.ScaleType.FIT_XY);
 i.setLayoutParams(new Gallery.LayoutParams(136, 88));

 // The preferred Gallery item background
 i.setBackgroundResource(mGalleryItemBackground);

 return i;
}

為Gallery 設置數據源:

[java]
// Reference the Gallery view  
Gallery g = (Gallery) findViewById(R.id.gallery); 
// Set the adapter to our custom adapter (below)  
g.setAdapter(new ImageAdapter(this)); 

// Reference the Gallery view
Gallery g = (Gallery) findViewById(R.id.gallery);
// Set the adapter to our custom adapter (below)
g.setAdapter(new ImageAdapter(this));

此外,應用提供registerForContextMenu 為Gallery添加一個Context Menu,可以參見Android ApiDemos示例解析(112):Views->Expandable Lists->1. Custom Adapter

 

 

作者:mapdigit

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *