Android Gallery component for cyclic display of images

Source: Internet
Author: User

The gallery component is primarily used to display a list of images horizontally, just as usual. The gallery component can only display the specified image in a limited way. That is, assuming that 10 images are specified for the gallery component, the Gallery component will not continue to appear when it is displayed to the 10th sheet. Although it doesn't matter most of the time, in some cases, we want the image to display to the last sheet and then the 1th one to start the display, which is the loop display. To implement such a style of gallery component, it is necessary to improve the gallery adapter object.

Traditional methods of using gallery components

recall the traditional use of the gallery component before implementing a gallery component that can cycle through the image. The gallery component is able to display a list of images horizontally, and when you click the next image of the current image, the image list moves to the left , and when you click the previous image of the current image, the image list moves to the right. You can also move the image list to the left and right by dragging. Currently shown is the 1th image of the effect 1 see. The gallery component shows the effect of the last image as seen in 2

Figure 1

Figure 2

As can be seen from Figure 2, when the last image is displayed, there is no image behind the list, which is also the basic display effect of the gallery component. The section later in this article will show you how to make the gallery component display to the last image from the 1th image.

OK, now let's see 11 and Figure 2 How the effect is made out of it. Gallery since it is used to display images, the 1th step requires some image files to display. You can now arbitrarily prepare some images. 6 jpg files (item1.jpg to item15.jpg) are prepared in the sample in this article. Place these files in the Res/drawable folder

The following is where the resource IDs for these images are stored in an int array, such as the following code:

private int[] Myimageids = {r.drawable.photo1, R.drawable.photo2, R.drawable.photo3, r.drawable.ph Oto4, R.drawable.photo5, R.dra Wable.photo6,};

In this example, the Main.xml file is configured with a gallery component, such as the following code:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/ Res/android "android:orientation=" vertical "android:layout_width=" fill_parent "android:layout_height=" fill_parent "> <gallery android:id=" @+id/gallery "android:layout_width=" fill_parent "android:layout_height=" Wrap_conte NT "android:layout_margintop=" 30DP "/></linearlayout>

Now load this component in the OnCreate method, such as the following code:

Public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.main);        Load Gallery assembly Gallery Gallery = (Gallery) Findviewbyid (r.id.gallery);         Create a Imageadapter object to describe the narrative image data Imageadapter imageadapter = new Imageadapter (this);    Sets the adapter object Gallery.setadapter (imageadapter) of the gallery component; }

A very important class is involved in the code above: Imageadapter. This class is a subclass of Android.widget.BaseAdapter, used to describe the narrative image information. Let's take a look at the complete code for this class:

 public class Imageadapter extends baseadapter {int mgalleryitembackground;        Private Context Mcontext;              Public Imageadapter (Context context) {Mcontext = context;            Get the properties of the Gallery component TypedArray TypedArray = Obtainstyledattributes (r.styleable.gallery); Mgalleryitembackground = Typedarray.getresourceid (r.styleable.gallery_android_galleryitembackground, 0                                );        }//Returns the total number of images public int GetCount () {return resids.length;        } public Object GetItem (int position) {return position;        } public long Getitemid (int position) {return position;            }//Returns the detailed location of the ImageView object public View getView (int position, view Convertview, ViewGroup parent) {             ImageView ImageView = new ImageView (mcontext); Sets the image of the current image (position is the position of the current image list) ImageView.Setimageresource (Myimageids[position]);            Imageview.setscaletype (ImageView.ScaleType.FIT_XY);            Imageview.setlayoutparams (New Gallery.layoutparams (163, 106));            Sets the background style of the gallery component Imageview.setbackgroundresource (mgalleryitembackground);        return imageView; }    }

Two points to note when writing the Imageadapter class:

1. The property information for the gallery component is obtained in the construction method of the Imageadapter class. This information is defined in the Res/values/attrs.xml file, such as the following code:

<?xml version= "1.0" encoding= "Utf-8"?><resources> <declare-styleable name= "Gallery" > <a TTR name= "Android:galleryitembackground"/> </declare-styleable></resources>

The above property information is used to set the background style of the gallery.

2. There are two important methods in the Imageadapter class: GetCount and GetView. The GetCount method is used to return the total number of images, it is important to note that the total number can not be greater than the actual number of images (can be less than the actual number of images), or will throw out the bounds of the exception. When the gallery component is about to display an image, the GetView method is called and the current image index (position parameters) is passed into the method. The general GetView method is used to return each component (ImageView object) that displays an image. From this point, it can be seen that the gallery component displays the image instantly, rather than displaying all of the images. In addition to creating the ImageView object in the GetView method, the image is displayed in ImageView with the corresponding image resource ID obtained from the resids array. Finally, the background display style of the gallery component is also set.

OK, now to execute this program, drag the image list back and forth, you will see 1 and Figure 2 see the effect.

The principle of cyclic display of images

The loop shows something similar to a circular list, and the next node of the last node is the 1th node. Looping through images can also simulate this.

Perhaps the attentive reader will find something in the Imageadapter class that was implemented in the previous section. Right! Is the relationship between the position and GetCount methods in the GetView method. The value of the position parameter is not likely to exceed the value returned by the GetCount method, that is, the range of position values is 0 to GetCount ()-1.

Assuming that the gallery component is displayed exactly to the last image, the position value is exactly getcount ()-1. So how do we get gallery to show the next image again? In other words, let position increase the value of 1, right! The return value of the GetCount () method is also increased by 1.

So here's another problem, assuming that position is infinitely added, it means that the myimageids array is going to grow, which consumes the resources of the system greatly. Think of this, you need to solve two problems: both position constantly add, and let the resids array to save the image resource ID is limited, how to do it? The GetCount () method is a good solution, allowing the GetCount method to return a very large number, such as Integer.max_value. The position can then increase as the image of the gallery component continues to move forward. Now the Myimageids array has only 6 elements, assuming that the value of position exceeds the bounds of the array, to continue looping through the elements in the array (that is, when the value of position is 6 o'clock, take the No. 0 element of the Myimageids array, which is 6 o'clock to take the 1th element), The simplest way is to take the remainder, code such as the following:

myimageids[position% myimageids.length]

In this section there are two improvements to the Imageadapter class, such as the following:

1. Make the GetCount method return a very large value. It is recommended to return Integer.max_value.

2. Loop through the GetView method to get the image resource ID in the Resids array by taking the remainder.

The above two improvements enable the image list to loop through the image as it moves to the right. Of course, such a method is essentially merely a pseudo-loop, that is, assuming that the image is actually moved to the value returned by the GetCount method, it is displayed to the last image. Just here the GetCount method returns the Integer.max_value, which is more than 2 billion, unless someone really wants to move the image to the No. 2 billion position, otherwise the gallery component looks like a component that loops through the image.

Implement a gallery component that loops through the display image

In this section, you will group out the complete code for the Imageadapter class that is related to looping the display image. Readers can see the two improvements described in the previous section. To make the interface look fuller, this example displays a magnified image (using the Imageswitcher component) below when you click an image in one of the gallery components. This example shows the effect of 3 as seen. As the images continue to move backwards, the image is constantly displayed and the reader is able to perform this example on its own.

The complete code for the main class in this example is the following:

Package IRDC. Ex04_10;import android.app.Activity; Import Android.os.Bundle; /* Class*/import Android.content.context;import android.content.res.typedarray;import Android.view.View to be used for this example; Import Android.view.viewgroup;import Android.widget.adapterview;import Android.widget.baseadapter;import Android.widget.gallery;import Android.widget.ImageView; Import Android.widget.toast;import Android.widget.adapterview.onitemclicklistener;public class EX04_10 extends activity{/** Called when the activity is first created. */@Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.main); /* Obtained via Findviewbyid */Gallery G = (Gallery) Findviewbyid (r.id.mygallery); /* Add a imageadapter and set to Gallery Object */G.setadapter (new Imageadapter (this)); /* Set a itemclicklistener and toast to the location of the selected picture */Settitle ("Gallery to realize the cycle of browsing the picture"); G.setonitemclicklistener (New Onitemclicklistener () {public void onItEmclick (adapterview parent, View v, int position, long id) {Toast.maketext (Ex04_10.this, getString (r.string.m Y_gallery_text_pre) + position + getString (r.string.my_gallery_text_post), Toast.length_short). Show (); } }); } public class Imageadapter extends Baseadapter/* Overwrite Baseadapter yourself define a imageadapter class */{int Mgaller Yitembackground; Private Context Mcontext; /* Imageadapter's constructor */private int[] Myimageids = {r.drawable.photo1, r.drawable.ph Oto2, R.drawable.photo3, R.drawable.photo4, R.drawable.photo5, R.drawable.photo6,}; Public Imageadapter (Context c) {mcontext = C; TypedArray a = obtainstyledattributes (r.styleable.gallery); /* Use the gallery attribute defined in Res/values/attrs.xml. */Mgalleryitembackground = A.getresourceid (r.styleable.gaLlery_android_galleryitembackground, 0); * Obtain the Gallery attribute of index a.recycle ();/* Make the Styleable property of the OBJECT reusable */} public int GetCount ()/* must be overridden by the party Method GetCount, the total number of pictures returned */{//return myimageids.length; return integer.max_value; } public Object GetItem (int position)/* must override the method GetItem, return position */{return position; } public long Getitemid (int position)/* must override the method Getitemid, return position */{return position; } public view GetView (int position, View Convertview, ViewGroup parent)/* Be sure to override the method GetView, return a View object */{//I F (Position = = GetCount ())//{//position = 0;//} ImageView i = new ImageView (mcontext); I.setimageresource (Myimageids[position%myimageids.length]); /* Set the picture to ImageView object */I.setscaletype (ImageView.ScaleType.FIT_XY); /* Once again set the width/height of the image */I.setlayoutparams (new Gallery.layoutparams (136, 88)); /* Set the layout width/height again */I.setbackgroundrEsource (Mgalleryitembackground); /* Set Gallery background image */return i; /* Return ImageView Object */}}}

2011-01-15

14:33:17

Android Gallery component for cyclic display of images

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.