Reprint Please specify source: http://blog.csdn.net/l1028386804/article/details/48049913
Today's Android development needs more and more, the effect is more and more cool, many Android apps to achieve the same image carousel on the PC website, then, how do the carousel effect of these images? Below, I will be with you to achieve these cool features.
First, the principle
First of all, the pictures and some of the text to be placed in a different data collection, the program starts by default display a set of pictures and text data, and then start a timer, every once in a while to replace the displayed picture and text data, while adding some animation effect, has reached the effect of the carousel. At the same time, we also want to achieve the effect of finger sliding picture to achieve the carousel.
Second, the implementation of 1, the program start interface mainactivity
I've put all the implementations in the mainactivity, so let's break it down to see the class.
1) member variables
These member variables include the controls displayed on the interface, an array of IDs that hold the images, an array of titles that hold the images, a custom viewpageradapter adapter, and a thread pool Scheduledexecutorservice
The specific code is as follows:
Private Viewpager mviewpaper;private list<imageview> images;private list<view> dots;private int currentitem;//record the position of the last point private int oldposition = 0;//store picture idprivate int[] Imageids = new Int[]{r.drawable.a, r.drawable.b,r.drawable.c,r.drawable.d,r.drawable.e};//the title of the picture is private string[] titles = new string[]{ " Gong Li is not vulgar, I can not vulgar ", " flutter the tree back! Re-sing the classic songs of the People Chorus ", " secret Beijing movie How to Upgrade ", " le video network TV version of the big delivery ", " blood cock silk anti-killing " };p rivate TextView title;private Viewpageradapter adapter;private Scheduledexecutorservice Scheduledexecutorservice;
2) OnCreate method
This method is the callback method when the program starts to create the interface, the main function of this method is to initialize the interface, and set the page Change listener event for Viewpager.
The specific implementation code is as follows:
@Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); mviewpaper = (Viewpager) Findviewbyid (R.ID.VP);//Picture shown images = new Arraylist<imageview > (); for (int i = 0, i < imageids.length; i++) {ImageView ImageView = new ImageView (this); Imageview.setbackgroundresou Rce (Imageids[i]); Images.add (ImageView);} Dot dots displayed = new arraylist<view> ();d Ots.add (Findviewbyid (r.id.dot_0));d Ots.add (Findviewbyid (r.id.dot_1)); Dots.add (Findviewbyid (r.id.dot_2));d Ots.add (Findviewbyid (r.id.dot_3));d Ots.add (Findviewbyid (R.id.dot_4)); = (TextView) Findviewbyid (r.id.title); Title.settext (Titles[0]); adapter = new Viewpageradapter (); Mviewpaper.setadapter (adapter); Mviewpaper.setonpagechangelistener (new Viewpager.onpagechangelistener () {@ overridepublic void onpageselected (int position) {Title.settext (titles[position]);d ots.get (position). Setbackgroundresource (r.drawable.dot_focused);d ots.get (oldposition). Setbackgroundresource (R.drawable.dot_normal); oldposition = Position;currentitem = position;} @Overridepublic void onpagescrolled (int arg0, float arg1, int arg2) {} @Overridepublic void onpagescrollstatechanged (int a rg0) {}});}
3) Custom Adapter class Viewpageradapter
This custom adapter class is different from the previous custom adapter class, which inherits the animation effect of the picture switch from the Pageradapter,pageradapter
The specific implementation code is as follows:
/** * Custom Adapter * @author Liuyazhuang * */private class Viewpageradapter extends pageradapter{@Overridepublic int Getcoun T () {return images.size ();} @Overridepublic boolean isviewfromobject (View arg0, Object arg1) {return arg0 = = arg1;} @Overridepublic void Destroyitem (viewgroup view, int position, object object) {//TODO auto-generated method STUB//SUPER.D Estroyitem (container, Position, object);//view.removeview (View.getchildat (position));//view.removeviewat ( position); View.removeview (Images.get (position));} @Overridepublic Object Instantiateitem (viewgroup view, int position) {//TODO auto-generated method Stubview.addview ( Images.get (position)); return images.get (position);}}
4) OnStart () method
This method is the interface creation completed, the callback method at startup, I do in this method is to create a thread pool to start a scheduled task, call a custom thread task, implementation of the timing to achieve the picture carousel effect.
The specific implementation code is as follows:
/** * Use thread pool timing to perform animated carousel */@Overrideprotected void OnStart () {//TODO auto-generated method Stubsuper.onstart (); Scheduledexecutorservice = Executors.newsinglethreadscheduledexecutor (); Scheduledexecutorservice.schedulewithfixeddelay (New Viewpagetask (), 2, 2, timeunit.seconds);
5) Picture Carousel Task Viewpagetask
This class implements the Runnable interface, implements the display of the picture carousel in the Run method, and notifies the UI thread through the handler, UI thread update interface shows that we don't need to pass any data here, so we can send an empty message by handler.
The specific implementation code is as follows:
/** * Photo Carousel Task * @author Liuyazhuang * */private class Viewpagetask implements runnable{@Overridepublic void Run () {Currenti TEM = (currentitem + 1)% imageids.length;mhandler.sendemptymessage (0);}}
6) Handler
Receive Viewpagetask message complete UI Update operation
The specific implementation code is as follows:
/** * Receive sub-line path handed over data */private Handler Mhandler = new Handler () {public void Handlemessage (Android.os.Message msg) {Mviewpape R.setcurrentitem (CurrentItem);};
7) OnStop
The main thing I do in this method is to stop the thread pool execution and release the thread pool resources.
The specific code is as follows:
@Overrideprotected void OnStop () {//TODO auto-generated method Stubsuper.onstop (); if (scheduledexecutorservice! = null) {Scheduledexecutorservice.shutdown (); scheduledexecutorservice = null;}}
8) The complete code is as follows:
Package Com.lyz.viewpage.activity;import Java.util.arraylist;import Java.util.list;import Java.util.concurrent.executors;import Java.util.concurrent.scheduledexecutorservice;import Java.util.concurrent.timeunit;import Android.app.activity;import Android.os.bundle;import Android.os.Handler; Import Android.support.v4.view.pageradapter;import Android.support.v4.view.viewpager;import Android.view.Menu; Import Android.view.view;import Android.view.viewgroup;import Android.widget.imageview;import android.widget.textview;/** * Program Main entrance * @author Liuyazhuang * */public class Mainactivity extends Activity {private ViewPage R mviewpaper;private list<imageview> images;private list<view> dots;private int currentItem;// Record the position of the last point private int oldposition = 0;//store picture idprivate int[] Imageids = new int[]{r.drawable.a,r.drawable.b,r.drawable.c , r.drawable.d,r.drawable.e};//store the title of the picture private string[] titles = new string[]{"Gong Li is not vulgar, I can not vulgar", "Flutter Tree back!" Sing the song of classical songs, "The Secret of the Beijing film Upgrade","Le video network TV version of the big delivery", "blood cock silk anti-killing"};p rivate TextView title;private viewpageradapter adapter;private scheduledexecutorse Rvice scheduledexecutorservice; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (r.layout.activity_main); mviewpaper = (Viewpager) Findviewbyid (R.ID.VP);// Displayed picture images = new arraylist<imageview> (); for (int i = 0; i < imageids.length; i++) {ImageView ImageView = new Image View (this); Imageview.setbackgroundresource (Imageids[i]); Images.add (ImageView);} Dot dots displayed = new arraylist<view> ();d Ots.add (Findviewbyid (r.id.dot_0));d Ots.add (Findviewbyid (r.id.dot_1)); Dots.add (Findviewbyid (r.id.dot_2));d Ots.add (Findviewbyid (r.id.dot_3));d Ots.add (Findviewbyid (R.id.dot_4)); = (TextView) Findviewbyid (r.id.title); Title.settext (Titles[0]); adapter = new Viewpageradapter (); Mviewpaper.setadapter (adapter); Mviewpaper.setonpagechangelistener (new Viewpager.onpagechangelistener () {@ overridepublic void onpageselected (int Position) {Title.settext (titles[position]);d ots.get (position). Setbackgroundresource (r.drawable.dot_focused); Dots.get (oldposition). Setbackgroundresource (r.drawable.dot_normal); oldposition = Position;currentitem = position;} @Overridepublic void onpagescrolled (int arg0, float arg1, int arg2) {} @Overridepublic void onpagescrollstatechanged (int a rg0) {}});} /** * Custom Adapter * @author Liuyazhuang * */private class Viewpageradapter extends pageradapter{@Overridepublic int Getcoun T () {return images.size ();} @Overridepublic boolean isviewfromobject (View arg0, Object arg1) {return arg0 = = arg1;} @Overridepublic void Destroyitem (viewgroup view, int position, object object) {//TODO auto-generated method STUB//SUPER.D Estroyitem (container, Position, object);//view.removeview (View.getchildat (position));//view.removeviewat ( position); View.removeview (Images.get (position));} @Overridepublic Object Instantiateitem (viewgroup view, int position) {//TODO auto-generated method Stubview.addview ( Images.get (position); return images.get (position);}} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.main, menu); return true;} /** * Use thread pool timing to perform animated carousel */@Overrideprotected void OnStart () {//TODO auto-generated method Stubsuper.onstart (); Scheduledexecutorservice = Executors.newsinglethreadscheduledexecutor (); Scheduledexecutorservice.schedulewithfixeddelay (New Viewpagetask (), 2, 2, timeunit.seconds); /** * Photo Carousel Task * @author Liuyazhuang * */private class Viewpagetask implements runnable{@Overridepublic void Run () {Currenti TEM = (currentitem + 1)% imageids.length;mhandler.sendemptymessage (0);}} /** * Receive sub-line path handed over data */private Handler Mhandler = new Handler () {public void Handlemessage (Android.os.Message msg) {Mviewpape R.setcurrentitem (CurrentItem);}; @Overrideprotected void OnStop () {//TODO auto-generated method Stubsuper.onstop (); if (scheduledexecutorservice! = null) {Scheduledexecutorservice.shutdown (); scheduledexecutorservice = null;}}}
2. Layout Activity_main.xml
The specific implementation code is as follows:
<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" match_parent "> <Fram Elayout android:layout_width= "match_parent" android:layout_height= "200dip" > <ANDROID.SUPPORT.V 4.view. Viewpager android:id= "@+id/vp" android:layout_width= "Match_parent" android:layout_height= "Match_parent"/> <linearlayout android:layout_width= "Match_parent" Android:layout_heig ht= "35dip" android:layout_gravity= "Bottom" android:background= "#33000000" android:gravity = "Center" android:orientation= "vertical" > <textview android:id= "@+id/title" Android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" Androi d:text= "Picture title" Android:tExtcolor= "@android: Color/white"/> <linearlayout android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:layout_margintop= "3dip" Android:orien tation= "Horizontal" > <view android:id= "@+id/dot_0" Android:lay Out_width= "5dip" android:layout_height= "5dip" android:layout_marginleft= "2dip" android:layout_marginright= "2dip" android:background= "@drawable/dot_focused"/> <view android:id= "@+id/dot_1" android:layout_width= "5dip" android:layout_height= "5dip" android:layout_marginleft= "2dip" Android:layout_ma rginright= "2dip" android:background= "@drawable/dot_normal"/> <view Android:id= "@+id/doT_2 "android:layout_width=" 5dip "android:layout_height=" 5dip "and roid:layout_marginleft= "2dip" android:layout_marginright= "2dip" android:background= "@drawable/dot_normal"/> <view android:id= "@+id/dot_3" Android: Layout_width= "5dip" android:layout_height= "5dip" android:layout_marginleft= "2dip" android:layout_marginright= "2dip" android:background= "@drawable/dot_normal"/> <view android:id= "@+id/dot_4" android:layout_width= "5dip" android:layout_height= "5dip" android:layout_marginleft= "2dip" Android:layout_ marginright= "2dip" android:background= "@drawable/dot_normal"/> </line Arlayout> </linearlayout> </FrameLayout></RelativeLayout>
3, Androidmanifest.xml
This file does not need to be updated.
The specific code is as follows:
<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android " package=" com.lyz.viewpage.activity " android:versioncode=" 1 " android:versionname=" 1.0 "> <uses-sdk android:minsdkversion= "Ten" android:targetsdkversion= "/> <application" android:allowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" android:theme= "@style/apptheme" > <activity android:name= " Com.lyz.viewpage.activity.MainActivity " android:label=" @string/app_name "> <intent-filter> <action android:name= "Android.intent.action.MAIN"/> <category android:name= " Android.intent.category.LAUNCHER "/> </intent-filter> </activity> </ Application></manifest>
Third, the Operation effect
Four, warm tips
You can go to link http://download.csdn.net/detail/l1028386804/9057555 download Android picture Carousel Effect implement full source code
In this example, for the sake of the aspect, I write some text directly in the layout file and the related class, Everyone in the real project to write these words in the String.xml file, in the external reference to these resources, remember, this is the most basic development knowledge and specifications as an Android programmer, I am here just to facilitate directly written in the class and layout files.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Android--The simplest image in history--the implementation of the Carousel advertisement effect