Gallery + imageswitcher implement simple electronic album

Source: Internet
Author: User

After learning about gallery + imageswitcher in Android, I found some information on the Internet and made a simple electronic album.

The automatic playback effect is achieved. You can use the double-click gesture to enable or disable automatic playback. Is king.




Main Implementation Code

Package COM. eebbk. elealbum. activity; import android. app. activity; import android. content. context; import android. content. res. typedarray; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. util. log; import android. view. gesturedetector; import android. view. keyevent; import android. view. motionevent; import android. view. view; import android. view. viewgroup; import android. View. gesturedetector. simpleongesturelistener; import android. view. viewgroup. layoutparams; import android. view. window; import android. view. windowmanager; import android. view. animation. animationutils; import android. widget. adapterview; import android. widget. adapterview. onitemselectedlistener; import android. widget. baseadapter; import android. widget. gallery; import android. widget. imageswitcher; import android. Widget. imageview; import android. widget. viewswitcher. viewfactory; public class mainactivity extends activity implements viewfactory, onitemselectedlistener, runnable {// flag for automatic playback private Boolean isplay = false; // automatic playback update message private final static int update = 1; // The current playback index value private int cur_index = 0; // gesturedetector is the gesture recognition class private gesturedetector mgesturedetector; private gallery = NULL; private imageswit Cher imageswitcher = NULL; private int [] imageids = new int [] {R. drawable. pic1, R. drawable. pic2, R. drawable. pic3, R. drawable. pic4, R. drawable. pic5, R. drawable. pic6, R. drawable. pic7, R. drawable. pic8 ,}; private handler = new handler () {@ overridepublic void handlemessage (Message MSG) {// todo auto-generated method stubif (MSG. what = Update) {Gallery. setselection (MSG. arg1);} super. handl Emessage (MSG) ;}};/** called when the activity is first created. * // @ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); // you can specify the value of requestwindowfeature (window. feature_no_title); // sets full screen getwindow (). setflags (windowmanager. layoutparams. flag_fullscreen, windowmanager. layoutparams. flag_fullscreen); setcontentview (R. layout. main); Init ();} private void Init () {mg Esturedetector = new gesturedetector (New mysimplegesture (); gallery = (Gallery) findviewbyid (R. id. gallery_id); Gallery. setadapter (New imageadaper (this); Gallery. setonitemselectedlistener (this); imageswitcher = (imageswitcher) findviewbyid (R. id. imageswitcher_id); imageswitcher. setfactory (this); // sets the effect of switching between fade in and fade out imageswitcher. setinanimation (animationutils. loadanimation (this, android. r. anim. Fade_in); imageswitcher. setoutanimation (animationutils. loadanimation (this, android. r. anim. fade_out);} @ overridepublic Boolean ontouchevent (motionevent event) {// todo auto-generated method stubmgesturedetector. ontouchevent (event); return Super. ontouchevent (event) ;}@ overridepublic Boolean onkeydown (INT keycode, keyevent event) {If (keycode = keyevent. keycode_back) {isplay = false;} return s Uper. onkeydown (keycode, event);}/* (non-javadoc) * @ see android. widget. viewswitcher. viewfactory # makeview () */@ overridepublic view makeview () {// todo auto-generated method stubimageview imageview = new imageview (this); imageview. setscaletype (imageview. getscaletype (). fit_center); imageview. setbackgroundcolor (0xff000000); imageview. setlayoutparams (New imageswitcher. layoutparams (layoutparams. fill_par Ent, layoutparams. fill_parent); Return imageview;} public class imageadaper extends baseadapter {context; int mgalleryitembackground; Public imageadaper (context) {This. context = context; typedarray = obtainstyledattributes (R. styleable. gallery); mgalleryitembackground = typedarray. getresourceid (R. styleable. gallery_android_galleryitembackground, 0); typedarray. recycle () ;} Public int getcount () {// todo auto-generated method stub return integer. max_value;} public object getitem (INT position) {// todo auto-generated method stub return imageids [position];} public long getitemid (INT position) {// todo auto-generated method stub return position;} public view getview (INT position, view convertview, viewgroup parent) {// todo auto-generated method stub imagevie W imageview = new imageview (this. context); imageview. setimageresource (imageids [position % imageids. length]); imageview. setscaletype (imageview. scaletype. fit_xy); imageview. setlayoutparams (new gallery. layoutparams (136, 88); imageview. setbackgroundresource (mgalleryitembackground); Return imageview ;}}/* (non-javadoc) * @ see android. widget. adapterview. onitemselectedlistener # onitemselected (Android. W Idget. adapterview, Android. View. View, Int, long) */@ overridepublic void onitemselected (adapterview <?> Parent, view, int position, long ID) {// After selecting an item in Gallery, switch to the image system. out. println ("position:" + Position + "cur_index:" + cur_index); imageswitcher. setimageresource (imageids [position % imageids. length]);}/* (non-javadoc) * @ see android. widget. adapterview. onitemselectedlistener # onnothingselected (Android. widget. adapterview) * // @ overridepublic void onnothingselected (adapterview <?> Parent) {// todo auto-generated method stub}/* (non-javadoc) * @ see Java. lang. runnable # Run () */@ overridepublic void run () {// todo auto-generated method stubwhile (isplay) {// cur_index = cur_index % imageids. length; message MSG = handler. obtainmessage (Update, cur_index, 0); handler. sendmessage (MSG); // The update interval is 2 s try {thread. sleep (2000);} catch (interruptedexception e) {// todo auto-generated Catch Block E. printstacktrace ();} cur_index ++;} private class mysimplegesture extends simpleongesturelistener {// trigger public Boolean ondoubletap (motionevent e) when the second touch is down) {// double-click to trigger automatic playback if (isplay = false) {isplay = true; new thread (mainactivity. this ). start () ;}else {isplay = false ;}return true ;}}}

Source code attachment: http://download.csdn.net/detail/tianmi1988/4914807

Gallery advanced applications

The above example is just the simplest gallery application. If we want to do something cool and cool:

1. The Gallery image can be played cyclically. After sliding to the right to the first image on the left, the last image needs to be displayed. After sliding to the left to the last image, the first image needs to be displayed continuously.

2. Highlight the selected image. If the Image Shadow is not selected, the selected image with the current focus is highlighted.

3. differentiate between click and selected image events and applicable scenarios

Effect 1 -- highlight

Not selected. In galleryactivity, set gallery. setunselectedalpha (0.3f); transparency to 0.3

Select, in getview (INT position, view convertview, viewgroup parent) of imageadapter, set imageview. setbackgroundcolor (color. Alpha (1); background color to 1

Effect 2 -- loop playback

Principle: The principle of gallery loop playback is similar to the idea of loop linked list. The first and last item connections are implemented through "remainder ".

1. In the getcount () method of imageadapter, modify the return value to infinity return integer. max_value;

Modify 2. In the getview (INT position, view convertview, viewgroup parent) method of imageadapter, set imageview. setimageresource (IMGs [position % IMGs. Length]); obtain the remainder

3. In galleryactivity, set gallery. setselection (imgadapter. IMGs. length * 100) to display the image position in the gallery from the middle (imgadapter. IMGs. length * 100)

Explanation:

Modify 1, mainly to make the loop close to an infinite reciprocating loop, so that the position is infinitely large, and the loop is not easy to end in practical applications (theoretically it will end, that is, 2 ^ 31-1 after about 2 billion cycles)

Modify 2 to allow reuse and display of the image through the remainder operation.

3. Because the start position is 0, sliding right to the left side will not be able to cycle (in this case, the left side will be-1, beyond the lower boundary of the IMGs [] array ), therefore, set the start position to imgadapter. IMGs. integer multiple of Length

Effect 3-click and select events

1. Click Event onitemclicklistener, which is triggered by clicking it by hand. It is not triggered when sliding.

2. The onitemselectedlistener event is automatically selected when the image slides to the center of the screen.

Applicable scenarios:

1. Click the onitemclicklistener event to perform logical processing only when you confirm that you want to select this item.

2. The selected event onitemselectedlistener can be used to remind the user of the current item that obtains the focus. If it is confirmed as this item, click onitemclicklistener to perform the next logical processing.

To enable the switchover without sound, you can configure Android: soundeffectsenabled = "false" in XML"

Complete advanced application code:

Activity

Importandroid. app. activity; importandroid. OS. bundle; importandroid. view. gravity; importandroid. view. view; importandroid. widget. adapterview; importandroid. widget. gallery; importandroid. widget. toast; publicclass galleryactivity extendsactivity {privateimageadapter imgadapter = NULL; // declare the image resource object privategallery gallery = NULL; @ override publicvoid oncreate (bundle savedinstancestate) {super. oncreate (S Avedinstancestate); setcontentview (R. layout. main); gallery = (Gallery) findviewbyid (R. id. gallery); imgadapter = newimageadapter (this); Gallery. setadapter (imgadapter); // sets the image resource Gallery. setgravity (gravity. center_horizontal); // sets the horizontal center to show Gallery. setselection (imgadapter. IMGs. length * 100); // you can specify the position of the starting image (which can be used to create a gallery loop display effect. setonitemclicklistener (clicklistener); // sets the listener event of the clicked image (triggered only when clicked by hand, but not when sliding)) Gallery. setonitemselectedlistener (selectedlistener); // sets the event of listening to the selected image (when the image slides to the center of the screen, it is regarded as automatically selected) Gallery. setunselectedalpha (0.3f); // sets the transparency Gallery of the unselected image. setspacing (40); // set the spacing between images} // click the picture listening event adapterview. onitemclicklistener clicklistener = newadapterview. onitemclicklistener () {@ override publicvoid onitemclick (adapterview <?> Parent, view, intposition, longid) {toast. maketext (galleryactivity. this, "Click image" + (Position + 1), 100 ). show () ;}; // The adapterview event of the selected image. onitemselectedlistener selectedlistener = newadapterview. onitemselectedlistener () {@ override publicvoid onitemselected (adapterview <?> Parent, view, intposition, longid) {toast. maketext (galleryactivity. this, "selected image" + (Position + 1), 20 ). show () ;}@ override publicvoid onnothingselected (adapterview <?> Arg0 ){}};}

Imageadapter. Java

Importandroid. content. context; importandroid. graphics. color; importandroid. view. view; importandroid. view. viewgroup; importandroid. widget. baseadapter; importandroid. widget. gallery; importandroid. widget. imageview; publicclass imageadapter extendsbaseadapter {privatecontext mcontext; // Image array source publicinteger [] IMGs = {R. drawable. img1, R. drawable. img2, R. drawable. img3, R. drawable. img4, R. drawable. img5, R. drawable. img6, R. drawable. img7}; publicimageadapter (context c) {mcontext = C ;}@ override publicint getcount () {returninteger. max_value;} // obtain the image position @ override publicobject getitem (intposition) {returnimgs [position];} // obtain the image ID @ override publiclong getitemid (intposition) {returnposition ;} @ override publicview getview (intposition, view convertview, viewgroup parent) {imageview = newimageview (mcontext); imageview. setimageresource (IMGs [position % IMGs. length]); imageview. setlayoutparams (newgallery. layoutparams (120); // set the layout image to 120 × display imageview. setscaletype (imageview. scaletype. center); // sets the display ratio type imageview. setbackgroundcolor (color. alpha (1); returnimageview ;}}


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.