Android-Implementation of the simplest image carousel advertisement effect in history,

Source: Internet
Author: User

Android-Implementation of the simplest image carousel advertisement effect in history,

Reprinted please indicate the source: http://blog.csdn.net/l1028386804/article/details/48049913

Nowadays, there are more and more Android development requirements and the effects are getting more and more cool. Many Android apps need to achieve the image carousel effects on PC websites. So, how is the carousel effect of these images achieved? Next, I will work with you to implement these cool functions.

I. Principles

First, place the images and text to be Carousel in different datasets respectively. When the program starts, a set of images and text data are displayed by default, and then a timer is started, the displayed image and text data are replaced at intervals, and some animation effects are added to achieve the carousel effect. At the same time, we also need to slide the image with our fingers to achieve the carousel effect.

II. Implementation 1. MainActivity on the program startup Interface

I put all the implementations in MainActivity. Let's take a look at this class.

1) member variables

These member variables include controls displayed on the interface, an array of image IDs, an array of image titles, a custom ViewPagerAdapter, and a thread pool ScheduledExecutorService.

The Code is as follows:

Private ViewPager mViewPaper; private List <ImageView> images; private List <View> dots; private int currentItem; // record the position of the previous vertex private int oldPosition = 0; // idprivate int [] imageIds = new int [] {R. drawable. a, R. drawable. b, R. drawable. c, R. drawable. d, R. drawable. e}; // the title of the image to be stored: private String [] titles = new String [] {" Li is not vulgar, so I can't be vulgar", "the tree is coming back! Sing a classic old song to attract a chorus of thousands of people "," reveal how Beijing movies are upgraded "," letv TV edition "," hot-blooded anti-Kill "}; private TextView title; private ViewPagerAdapter adapter; private ScheduledExecutorService scheduledExecutorService;

2) onCreate Method

This method is the callback method when the program starts creating the interface. The main function of this method is to initialize the interface and set page change listening events 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); // The displayed image images = new ArrayList <ImageView> (); for (int I = 0; I <imageIds. length; I ++) {ImageView imageView = new ImageView (this); imageView. setBackgroundResource (imageIds [I]); images. add (imageView);} // The displayed dot dots = new ArrayList <View> (); dots. add (findViewById (R. id. dot_0); dots. add (findViewById (R. id. dot_1); dots. add (findViewById (R. id. dot_2); dots. add (findViewById (R. id. dot_3); dots. add (findViewById (R. id. dot_4); title = (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]); dots. 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 arg0) {}});}

3) custom Adapter class ViewPagerAdapter

This custom Adapter class is different from the previous custom Adapter class. It inherits from PagerAdapter and implements the animation effect of image switching in PagerAdapter.

The specific implementation code is as follows:

/*** Custom Adapter ** @ author liuyazhuang **/private class ViewPagerAdapter extends PagerAdapter {@ Overridepublic int getCount () {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. destroyItem (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 callback method when the interface is created and started. What I have done in this method is to create a thread pool to start a scheduled scheduling task and call a custom thread task, implement the image carousel effect at regular intervals.

The specific implementation code is as follows:

/*** Use the thread pool to regularly execute animation carousel */@ Overrideprotected void onStart () {// TODO Auto-generated method stubsuper. onStart (); scheduledExecutorService = Executors. newSingleThreadScheduledExecutor (); scheduledExecutorService. scheduleWithFixedDelay (new ViewPageTask (), 2, 2, TimeUnit. SECONDS );}

5) ViewPageTask

This class implements the Runnable interface, implements the image carousel Display Effect in the run method, and notifies the UI thread through handler, the UI thread updates the interface display, here we do not need to transmit any data, therefore, send an empty message through handler.

The specific implementation code is as follows:

/*** Image carousel task * @ author liuyazhuang **/private class ViewPageTask implements Runnable {@ Overridepublic void run () {currentItem = (currentItem + 1) % imageIds. length; mHandler. sendEmptyMessage (0 );}}

6) handler

Receives the ViewPageTask message to complete the UI update operation.

The specific implementation code is as follows:

/*** Receive data transmitted by the Sub-thread */private Handler mHandler = new Handler () {public void handleMessage (android. OS. message msg) {mViewPaper. setCurrentItem (currentItem );};};

7) onStop

The main operation I implemented in this method is to stop the execution of the thread pool and release the thread pool resources.

The 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; I Mport android. view. view; import android. view. viewGroup; import android. widget. imageView; import android. widget. textView;/*** main program entry * @ author liuyazhuang **/public class MainActivity extends Activity {private ViewPager mViewPaper; private List <ImageView> images; private List <View> dots; private int currentItem; // record the position of the previous point private int oldPosition = 0; // The idprivate int [] imageIds = new int [] {R. drawable. A, R. drawable. b, R. drawable. c, R. drawable. d, R. drawable. e}; // the title of the image to be stored: private String [] titles = new String [] {" Li is not vulgar, so I can't be vulgar", "the tree is coming back! Sing a classic old song to attract a chorus of thousands of people "," reveal how Beijing movies are upgraded "," letv TV edition "," hot-blooded anti-Kill "}; private TextView title; private ViewPagerAdapter adapter; private ScheduledExecutorService scheduledExecutorService; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); mViewPaper = (ViewPager) findViewById (R. id. vp); // The displayed image images = new ArrayList <ImageView> (); for (int I = 0; I <imageIds. length; I ++) {ImageView imageView = new ImageView (this); imageView. setBackgroundResource (imageIds [I]); images. add (imageView);} // The displayed dot dots = new ArrayList <View> (); dots. add (findViewById (R. id. dot_0); dots. add (findViewById (R. id. dot_1); dots. add (findViewById (R. id. dot_2); dots. add (findViewById (R. id. dot_3); dots. add (findViewById (R. id. dot_4); title = (TextView) findViewById (R. id. title); ti Tle. setText (titles [0]); adapter = new ViewPagerAdapter (); mViewPaper. setAdapter (adapter); mViewPaper. setOnPageChangeListener (new ViewPager. onPageChangeListener () {@ Overridepublic void onPageSelected (int position) {title. setText (titles [position]); dots. get (position ). setBackgroundResource (R. drawable. dot_focused); dots. get (oldPosition ). setBackgroundResource (R. drawable. dot_normal); oldPosition = position; cu RrentItem = position ;}@ Overridepublic void onPageScrolled (int arg0, float arg1, int arg2) {}@ Overridepublic void onPageScrollStateChanged (int arg0 ){}});} /*** custom Adapter ** @ author liuyazhuang **/private class ViewPagerAdapter extends PagerAdapter {@ Overridepublic int getCount () {return images. size () ;}@ Overridepublic boolean isViewFromObject (View arg0, Object arg1) {return arg0 = arg1 ;}@ Overridep Ublic void destroyItem (ViewGroup view, int position, Object object) {// TODO Auto-generated method stub/super. destroyItem (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 (positi On); return images. get (position) ;}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true;}/*** use the thread pool to regularly execute animation carousel */@ Overrideprotected void onStart () {// TODO Auto-generated method stubsuper. onStart (); scheduledExecutorService = Executors. newSingleThreadScheduledExecutor (); ScheduledExecutorService. scheduleWithFixedDelay (new ViewPageTask (), 2, 2, TimeUnit. SECONDS);}/*** image carousel task * @ author liuyazhuang **/private class ViewPageTask implements Runnable {@ Overridepublic void run () {currentItem = (currentItem + 1) % imageIds. length; mHandler. sendEmptyMessage (0) ;}}/*** receives data transmitted by the subthread */private Handler mHandler = new Handler () {public void handleMessage (android. OS. message msg) {MViewPaper. 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"> <FrameLayout android: layout_width = "match_parent" android: layout_height = "200dip"> <android. support. v4.view. viewPager android: id = "@ + id/vp" android: layout_width = "match_parent" android: layout_height = "match_parent"/> <LinearLayout android: layout_width = "match_parent" android: layout_height = "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" android: text = "image title" android: textColor = "@ android: color/white "/> <LinearLayout android: layout_width =" wrap_content "android: layout_height =" wrap_content "android: layout_marginTop =" 3dip "android: orientation = "horizontal"> <View android: id = "@ + id/dot_0" android: layout_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_marginRight = "2dip" android: background = "@ drawable/dot_normal"/> <View android: id = "@ + id/dot_2" 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_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: authorization = "2dip" android: layout_marginRight = "2dip" android: background = "@ drawable/dot_normal"/> </LinearLayout> </FrameLayout> </RelativeLayout>

3. AndroidManifest. xml

This file does not need to be updated.

The 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="10"        android:targetSdkVersion="18" />    <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>

Iii. Running Effect

4. Tips

You can go to the links

In this example, for the purpose of writing some text directly in the layout file and related classes, you need to write these words in the real project. in xml files, reference these resources externally. Remember, this is the most basic development knowledge and specification for an Android programmer. I am writing these resources in the class and layout files for convenience.

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.