Gallery, ListView, and Spinner share one thing in common. They are subclasses of AdapterView. The display of AdapterView can be achieved through data binding. The data source can be an array or database record, and the data source and AdapterView can be a bridge through Adapter. Using the Adapter, AdatperView can display data sources or process user selection events, such as selecting an item in the list.
Gallery displays a list horizontally and centers the selected list items. Usually used to display a group of images. In general, getView of the Adapter can return any type of View. (Such as TextView ).
In this example, an ImageAdapter is created by extending BaseAdapter to display a group of images in the/res/drawable directory. The corresponding resource ID is as follows:
[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
};
The getView of this Adpater is defined as follows and an ImageView is returned:
[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;
}
Set the data source for 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 ));
In addition, the application provides registerForContextMenu to add a Context Menu for Gallery. For details, see Android ApiDemos example resolution (112): Views-> Expandable Lists-> 1. Custom Adapter
Author: mapdigit