Android ApiDemos樣本解析(119):Views->Gallery->1. P

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.