In Android, imageswitcher uses gallery to display the resource images in the SD card.

Source: Internet
Author: User

This article mainly describes how imageswitcher combines the gallery component to display the resource images in sdcard. I believe you have read this example in API demo, however, the example in the API demo shows the resource images under the drawable directory in the project, which makes it easier to call the system API. However, during the project development process, however, some images cannot be completely determined. For example, you need to display the images taken by the camera and the resource images under a directory in sdcard. In fact, the system also provides the corresponding API for our application to implement this function. The following uses an example different from the API demo to show how to implement this function.

[1] let's take a look at the structure of the Code in this example:

The Code of each file is directly listed below. I will not explain it in detail here. I will see the implementation at last...

[2] source code of RES/layout/Main. xml file:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical"     android:background="#55000000" >        <TextView         android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:gravity="center"        android:text="Welcome to Andy.Chen's Blog!"        android:textSize="20sp"/>        <ImageSwitcher        android:id="@+id/switcher"        android:layout_width="wrap_content"        android:layout_height="350dip"        android:layout_alignParentLeft="true"        android:layout_alignParentRight="true" />    <Gallery        android:id="@+id/mygallery"        android:layout_width="fill_parent"        android:layout_height="80dp"        android:layout_alignParentBottom="true"        android:layout_alignParentLeft="true"        android:gravity="center_vertical"        android:spacing="16dp" />    </LinearLayout>

[3] source code of the res/values/attrs. xml file:

<?xml version="1.0" encoding="utf-8"?><resources>      <declare-styleable name="Gallery">     <attr name="android:galleryItemBackground" />   </declare-styleable>     </resources>

[4] imageswitcherandgallerydemoactivity. Java source code: (the source code of this class is quite a lot. Please be patient)

Package COM. andyidea. imagedemo; import Java. io. file; import Java. util. arraylist; import Java. util. list; import android. app. activity; import android. content. context; import android. content. res. typedarray; import android. graphics. bitmap; import android. graphics. bitmapfactory; import android.net. uri; import android. OS. bundle; import android. OS. environment; import android. util. log; import android. view. view; import Ndroid. view. view. onclicklistener; import android. view. viewgroup; import android. view. animation. animationutils; import android. widget. adapterview; import android. widget. adapterview. onitemclicklistener; import android. widget. adapterview. onitemselectedlistener; import android. widget. baseadapter; import android. widget. gallery; import android. widget. gallery. layoutparams; import android. widget. imageswitcher; impo RT android. widget. imageview; import android. widget. toast; import android. widget. viewswitcher. viewfactory;/*** how does imageswitcher and gallery display the resource images in the SD card * @ author Andy. chen * @ Email: Chenjunjun.ZJ@gmail.com */public class imageswitcherandgallerydemoactivity extends activity implements onitemselectedlistener, viewfactory {private list <string> imagepathlist; private string [] list; private imageswitcher mswitch Er; private gallery mgallery;/** called when the activity is first created. * // @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); imagepathlist = getimagepathfromsd (); List = imagepathlist. toarray (New String [imagepathlist. size ()]);/* sets switcher */mswitcher = (imageswitcher) findviewbyid (R. id. switcher); mswitcher. setfactory (Th Is);/* set the switcher Loading Mode */mswitcher. setinanimation (animationutils. loadanimation (this, android. r. anim. fade_in);/* set the switcher output mode */mswitcher. setoutanimation (animationutils. loadanimation (this, android. r. anim. fade_out); mswitcher. setonclicklistener (New onclicklistener () {public void onclick (view v) {toast. maketext (imageswitcherandgallerydemoactivity. this, "you clicked the image on imageswitch", toast. length_short ). show () ;}}); Mgallery = (Gallery) findviewbyid (R. id. mygallery);/* add several imageadapters and set them to the gallery object */mgallery. setadapter (New imageadapter (this, getimagepathfromsd (); mgallery. setonitemselectedlistener (this);/* set an itemclicklistener event */mgallery. setonitemclicklistener (New onitemclicklistener () {public void onitemclick (adapterview <?> Parent, view V, int position, long ID) {toast. maketext (imageswitcherandgallerydemoactivity. this, "you clicked the image on Gallery", toast. length_short ). show () ;}}) ;}/ ** obtain the path of the resource image from the SD card */private list <string> getimagepathfromsd () {/* set the current path */list <string> it = new arraylist <string> (); // read the path string ImagePath = environment of the resource image in the sdcard as needed. getexternalstoragedirectory (). tostring () + "/hknational/image"; file mfile = N EW file (ImagePath); file [] files = mfile. listfiles ();/* save all files to arraylist */For (INT I = 0; I <files. length; I ++) {file = files [I]; If (checkisimagefile (file. getpath () it. add (file. getpath ();} return it;}/** determine the image format */private Boolean checkisimagefile (string fname) {Boolean isimageformat; /* Get the extension */string end = fname. substring (fname. lastindexof (". ") + 1, fname. length ()). tolowercase ();/* scale The name type determines mimetype */If (end. equals ("jpg") | end. equals ("GIF") | end. equals ("PNG") | end. equals ("Jpeg") | end. equals ("BMP") {isimageformat = true;} else {isimageformat = false;} return isimageformat ;} /* rewrite baseadapter to customize an imageadapter class */public class imageadapter extends baseadapter {/* declaration variable */INT mgalleryitembackground; private context mcontext; private list <string> Lis; /* imageadapter constructor */publ IC imageadapter (context c, list <string> Li) {mcontext = C; Lis = Li;/** use Res/values/attrs. the gallery attribute defined by <declare-styleable> in XML. */typedarray mtypearray = obtainstyledattributes (R. styleable. gallery);/* obtain the index ID of the gallery attribute */mgalleryitembackground = mtypearray. getresourceid (R. styleable. gallery_android_galleryitembackground, 0);/* enables the object's styleable attribute to be used repeatedly */mtypearray. recycle ();}/* rewrite the getcount method to return the image Number */Public int getcount () {return Lis. size ();}/* override method getitem, return position */public object getitem (INT position) {return position;}/* override method getitemid, pass and position */public long getitemid (INT position) {return position;}/* rewrite the getview method, and pass several view objects */public view getview (INT position, view convertview, viewgroup parent) {/* generate the imageview object */imageview I = new imageview (mcontext);/* set the image to the imageview object */bitmap B M = bitmapfactory. decodefile (LIS. get (position ). tostring (); I. setimagebitmap (BM);/* reset the width and height of the image */I. setscaletype (imageview. scaletype. fit_xy);/* reset the width and height of Layout */I. setlayoutparams (new gallery. layoutparams (136, 88);/* set the gallery background image */I. setbackgroundresource (mgalleryitembackground);/* returns the imageview object */return I ;}@ overridepublic view makeview () {imageview IV = new imageview (this); IV. setbackgroundcolor (0 Xff000000); IV. setscaletype (imageview. scaletype. fit_center); IV. setlayoutparams (New imageswitcher. layoutparams (layoutparams. fill_parent, layoutparams. fill_parent); Return IV ;}@ overridepublic void onitemselected (adapterview <?> Parent, view, int position, long ID) {// todo auto-generated method stubstring photourl = list [position]; log. I ("A", String. valueof (position); mswitcher. setimageuri (URI. parse (photourl) ;}@ overridepublic void onnothingselected (adapterview <?> Parent) {// todo auto-generated method stub }}

[5] The program runs as follows:

This is all done!

This article is original by Andy. Chen. You are welcome to repost it. Please indicate the source for reprinting. Thank you for your attention.

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.