Android's gridview and gallery combined with demo

Source: Internet
Author: User

Demo Introduction: the home page is a gridview loaded image. Three pictures are displayed on the vertical screen, and four pictures are displayed on the horizontal screen. The image size is limited and the gray border is added.

Clicking an image will link to the gallery page. Because the sliding effect of the gallery control in Android is very poor (a sliding operation will load many images at a time), the gallery is expanded here, slide to load only one image at a time.

The demo effect is as follows:

 

1. gridviewactivity. Java on the homepage activity page:

Public class gridviewactivity extends activity {private displaymetrics DM; private gridimageadapter IA; private gridview g; private int imagecol = 3; @ overrideprotected void oncreate (bundle savedinstancestate) {// todo auto-generated method stubsuper. oncreate (savedinstancestate); // requestwindowfeature (window. feature_no_title); IA = new gridimageadapter (this); setcontentview (R. layout. mygridview); G = (gridview) findviewbyid (R. id. mygrid); G. setadapter (IA); G. setonitemclicklistener (New onitemclick (this); // get the screen size dm = new displaymetrics (); getwindowmanager (). getdefadisplay display (). getmetrics (DM);}/*** processing during screen switching. If the screen is a portrait screen, three columns are displayed. If the screen is a landscape screen, four columns */@ overridepublic void onconfigurationchanged (configuration newconfig) {try {super. onconfigurationchanged (newconfig); // If the screen is landscape, three columns are displayed. If the screen is landscape, four columns are displayed if (this. getresources (). getconfiguration (). orientation = configuration. orientation_landscape) {imagecol = 4;} else if (this. getresources (). getconfiguration (). orientation = configuration. orientation_portrait) {imagecol = 3;} G. setnumcolumns (imagecol); G. setadapter (New imageadapter (this); // IA. policydatasetchanged ();} catch (exception ex) {ex. printstacktrace () ;}}/***** @ author when you click a small image, it is linked to the gridviewactivity page, load and display */public class onitemclick implements onitemclicklistener {public onitemclick (context c) {mcontext = C ;}@ overridepublic void onitemclick (adapterview aview, view, int position, long arg3) {intent = new intent (); intent. setclass (gridviewactivity. this, galleryactivity. class); intent. putextra ("position", position); gridviewactivity. this. startactivity (intent);} private context mcontext;}/***** @ author empty mountain do not empty set the gridview image adapter */public class gridimageadapter extends baseadapter {drawable btndrawable; public gridimageadapter (context c) {mcontext = C; Resources resources = C. getresources (); btndrawable = resources. getdrawable (R. drawable. BG);} public int getcount () {return imagesource. mthumbids. length;} public object getitem (INT position) {return position;} public long getitemid (INT position) {return position;} public view getview (INT position, view convertview, viewgroup parent) {imageviewext imageview; If (convertview = NULL) {imageview = new imageviewext (mcontext); // If the screen is landscape, the gridview displays four images, you need to set the image size if (imagecol = 4) {imageview. setlayoutparams (New gridview. layoutparams (DM. heightpixels/imagecol-6, DM. heightpixels/imagecol-6);} else {// if it is a portrait screen, the gridview will display three columns of images. You need to set the image size to imageview. setlayoutparams (New gridview. layoutparams (DM. widthpixels/imagecol-6, DM. widthpixels/imagecol-6);} imageview. setadjustviewbounds (true); imageview. setscaletype (imageview. scaletype. center_crop);} else {imageview = (imageviewext) convertview;} imageview. setimageresource (imagesource. mthumbids [position]); Return imageview;} private context mcontext ;}}

Load the gridview page. If the screen is a vertical screen, three columns are displayed. If the screen is a horizontal screen, four columns are displayed. The displayed image is added with a gray border, here, the imageviewext class is referenced in the getview method of the adapter gridimageadapter to process images. This class is extended from imageview. Click an image to go to The galleryactivity page.

2. imageviewext. Java File

/***** @ Author empty mountain not empty * extend the imageview class and add a border to the image, and set the border to gray */public class imageviewext extends imageview {// Add the border to the gray private int color; Public imageviewext (context) {super (context ); // todo auto-generated constructor stub color = color. gray;} public imageviewext (context, attributeset attrs) {super (context, attrs); // todo auto-generated constructor stub color = color. gray;} @ override protected void ondraw (canvas) {// todo auto-generated method stub super. ondraw (canvas); // draw the border rect rec = canvas. getclipbounds (); Rec. bottom --; Rec. right --; paint = new paint (); paint. setcolor (color); paint. setstrokewidth (5); paint. setstyle (paint. style. stroke); canvas. drawrect (REC, paint );}}

You can reload the ondraw method to draw borders and set border colors.

3. album galleryactivity. Java

 
/***** @ Author empty mountain not empty * gallery image page, use intent to get the position of the image passed by the gridview, load the image, set the adapter */public class galleryactivity extends activity {public int I _position = 0; private displaymetrics DM; @ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); requestwindowfeature (window. feature_no_title); setcontentview (R. layout. mygallery); DM = new displaymetrics (); getwindowmanager (). getdefadisplay display (). getmetrics (DM); // obtain the gallery object galleryext G = (galleryext) findviewbyid (R. id. ga); // use intent to obtain the position intent = getintent (); I _position = intent. getintextra ("position", 0); // Add the imageadapter to the gallery object imageadapter IA = new imageadapter (this); G. setadapter (IA); G. setselection (I _position); // load the animation an = animationutils. loadanimation (this, R. anim. scale); G. setanimation ();}}

There are three points:

(1) Extend the gallery component, that is, the galleryext control, set to slide only one image at a time, and if it is the first image, sliding to the left will prompt "to the first page". If it is the last image, sliding to the right will prompt "to the next page"

(2) receive the position parameter from the gridviewactivity page, find the specific image through this parameter, and load it through the imageadapter

(3) imageadapter for image loading

4. galleryext. Java File

/***** @ Author empty mountain not empty * extended gallery component, set to slide only one image at a time, and * if it is the first image, sliding to the left will prompt "to the first page" * if it is the last image, sliding to the right will prompt "to the next page" */public class galleryext extends gallery {Boolean is_first = false; Boolean is_last = false; Public galleryext (context) {super (context); // todo auto-generated constructor stub} public galleryext (context, attributeset paramattributeset) {super (context, paramattributeset);} private Boolean isscrollingleft (motionevent E1, motionevent E2) {return e2.getx ()> e1.getx () ;}@ override public Boolean onfling (motionevent E1, motionevent E2, float distancex, float distancey) {// refactor the onfling method, slide the gallery control to load only one image at a time // obtain the adapter imageadapter IA = (imageadapter) This. getadapter (); // get the position of the current image in the image resource. Int P = IA. getownposition (); // The total number of images int COUNT = IA. getcount (); int kevent; If (isscrollingleft (E1, E2) {// check if scrolling left if (P = 0 & is_first) {// when the first page is moved to the left, the toast message is displayed. maketext (this. getcontext (), "to the first page", toast. length_short ). show ();} else if (P = 0) {// when the first page is reached, set is_first to true is_first = true;} else {is_last = false ;} kevent = keyevent. keycode_dpad_left;} else {// otherwise scrolling right IF (P = count-1 & is_last) {toast. maketext (this. getcontext (), "to the last page", toast. length_short ). show ();} else if (P = count-1) {is_last = true;} else {is_first = false;} kevent = keyevent. keycode_dpad_right;} onkeydown (kevent, null); Return true ;}

5. imageadapter. Java file

/***** @ Author empty mountain not empty * image adapter, used to load images */public class imageadapter extends baseadapter {// image adapter // define context private int ownposition; public int getownposition () {return ownposition;} public void setownposition (INT ownposition) {This. ownposition = ownposition;} private context mcontext; // define an integer array, that is, the image source. // declare imageadapterpublic imageadapter (context c) {mcontext = C ;} // obtain the number of images public int getcount () {return imagesource. mthumbids. length ;}// obtain the position of the image in the library public object getitem (INT position) {ownposition = position; return position ;}// obtain the image idpublic long getitemid (INT position) {ownposition = position; return position;} public view getview (INT position, view convertview, viewgroup parent) {ownposition = position; imageview = new imageview (mcontext); imageview. setbackgroundcolor (0xff000000); imageview. setscaletype (imageview. scaletype. fit_center); imageview. setlayoutparams (New galleryext. layoutparams (layoutparams. match_parent, layoutparams. match_parent); imageview. setimageresource (imagesource. mthumbids [position]); // imageview. setadjustviewbounds (true); // imageview. setlayoutparams (New gridview. layoutparams (320,480); // imageview. setscaletype (imageview. scaletype. center_inside); Return imageview ;}}

6. Configuration File

(1) androidmanifest. xml:

 
<? XML version = "1.0" encoding = "UTF-8"?> <Manifest xmlns: Android = "http://schemas.android.com/apk/res/android" package = "com. ajie "Android: versioncode =" 1 "Android: versionname =" 1.0 "> <application Android: icon =" @ drawable/icon "Android: label = "@ string/app_name"> <activity Android: Name = ". galleryactivity "Android: Label =" @ string/Title "/> <activity Android: Name = ". gridviewactivity "Android: Label =" @ string/app_name "Android: configchanges =" orientation | keyboardhidden "> <intent-filter> <action Android: Name =" android. intent. action. main "/> <category Android: Name =" android. intent. category. launcher "/> </intent-filter> </activity> </Application> </manifest>

(2) mygridview. XML, that is, the gridview page

<? XML version = "1.0" encoding = "UTF-8"?> <Gridview xmlns: Android = "http://schemas.android.com/apk/res/android" Android: Id = "@ + ID/mygrid" Android: layout_width = "fill_parent" Android: layout_height = "fill_parent" Android: verticalspacing = "6dp" Android: numcolumns = "3" Android: paddingtop = "5dp" Android: stretchmode = "columnwidth" Android: gravity = "fill_vertical | fill_horizontal"/>

(3) mygallery. xml: load the image page

<? XML version = "1.0" encoding = "UTF-8"?> <Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: Orientation = "horizontal" Android: layout_width = "match_parent" Android: layout_height = "match_parent" Android: gravity = "center" Android: padding = "10dip"> <relativelayout Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: padding = "2dip" Android: background = "#000000"> <COM. ajie. galleryext Android: Id = "@ + ID/Ga" Android: layout_width = "fill_parent" Android: layout_height = "fill_parent" Android: spacing = "16dp"/> </relativelayout> </linearlayout>

Demo: <a href = "http://files.cnblogs.com/fbsk/gridGalleryDemo.zip"> gridgallerydemo.zip download </a>

 

Related Article

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.