The Android mobile operating system has many controls that can help us easily implement some functions. Here we will introduce you in detail how to use the Android Gallery control, hoping to help you gain an in-depth understanding of the use of the control.
Android Gallery Control: An Image Browsing Control
Layout part:
- < Gallery xmlns:android=
"http://schemas.android.com/apk/res/android"
- android:id="@+id/gallery"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"/>
Android Gallery control code:
Code of the main class:
- Gallery g = (Gallery) findViewById (R. id. gallery );
// Define the Gallery Control
- G. setAdapter (new ImageAdapter (this ));
// Set the image source of the Gallery Control
- G. setOnItemClickListener (new OnItemClickListener (){
// Click to listen to events
- Public void onItemClick (AdapterView parent, View v,
Int position, long id) {// Click Event
- Toast. makeText (galleryMain. this, "" + position,
Toast. LENGTH_SHORT). show (); // Toast
- }
- });
ImageAdapter class
- Private Context mContext;
- // Define Context
- Private Integer [] mImageIds = {
- // Define an integer array, that is, the image source.
- R. drawable. sample_1,
- R. drawable. sample_2,
- R. drawable. sample_3,
- R. drawable. sample_4,
- R. drawable. sample_5,
- R. drawable. sample_6,
- R. drawable. sample_7
- };
- Public ImageAdapter (Context c ){
- // Declare ImageAdapter
- MContext = c;
- }
- Public int getCount () {// obtain the number of images
- Return mImageIds. length;
- }
- Public Object getItem (int position ){
- // Obtain the image location in the library
- Return position;
- }
- Public long getItemId (int position ){
- // Obtain the image location in the library
- Return position;
- }
- Public View getView (int position, View convertView,
ViewGroup parent ){
- ImageView I = new ImageView (mContext );
- I. setImageResource (mImageIds [position]);
- // Set resources for ImageView
- I. setLayoutParams (new Gallery. LayoutParams (200,200 ));
- // Set the layout image to 200x200
- I. setScaleType (ImageView. ScaleType. FIT_XY );
- // Set the proportion type
- Return I;
- }
The usage of the Android Gallery control is described here.