Android development: ViewPager for automatically scrolling labels of images,

Source: Internet
Author: User

Android development: ViewPager for automatically scrolling labels of images,

In Android, Image Auto-scrolling is very common. We can use our own animations to implement the function. But in Android provides a ViewPager class, to achieve the rolling effect, in the Android extras directory under the android-support-vx.jar, x represents version 4, 7 and so on. During use, we need the ViewPager tag of android. support. v4.view. viewPager.

Blog Source: Http://blog.csdn.net/fengshizty

The code is very simple and does not need to be explained:


The xml layout file 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"    tools:context="com.andy.viewpagedemo.MainActivity" >    <android.support.v4.view.ViewPager        android:id="@+id/viewPager"        android:layout_width="wrap_content"        android:layout_height="200dip" />    <LinearLayout        android:layout_alignBottom="@id/viewPager"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:background="#33000000"        android:orientation="vertical" >        <TextView            android:id="@+id/image_desc"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:gravity="center"            android:text="@string/app_name"            android:textColor="@android:color/white"            android:textSize="18sp" />        <LinearLayout            android:id="@+id/point_group"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_gravity="center"            android:orientation="horizontal"             >        </LinearLayout>    </LinearLayout></RelativeLayout>

The Activity code is as follows:

Package com. andy. viewpagedemo; import java. util. arrayList; 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. support. v4.view. viewPager. onPageChangeListener; import android. view. view; import android. view. viewGroup; import android. widget. imageView; import android. widget. linearLay Out; import android. widget. textView; public class MainActivity extends Activity {private ViewPager viewPager; private LinearLayout point_group; private TextView image_desc; // image resource idprivate final int [] images = {R. drawable. a, R. drawable. b, R. drawable. c, R. drawable. d, R. drawable. e}; // image title set private final String [] imageDescriptions = {" Li is not vulgar, so I can't be vulgar", "It's coming back! Sing a classic old song to attract a chorus of thousands of people, "reveal how Beijing movies are upgraded", "letv TV edition big delivery", "hot-blooded anti-Kill"}; private ArrayList <ImageView> imageList; // The Position of the previous page protected int lastPosition = 0; // determine whether to automatically scroll viewPagerprivate boolean isRunning = true; private Handler handler = new Handler () {public void handleMessage (android. OS. message msg) {// run the slide to the next page viewPager. setCurrentItem (viewPager. getCurrentItem () + 1); if (isRunning) {// send a handler delay handler. sendEmptyMessageDelayed (0, 2000) ;}};@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); viewPager = (ViewPager) findViewById (R. id. viewPager); point_group = (LinearLayout) findViewById (R. id. point_group); image_desc = (TextView) findViewById (R. id. image_desc); image_desc.setText (imageDescriptions [0]); // initialize the image resource imageList = new ArrayList <ImageView> (); for (int I: images) {// initialize the image resource ImageView imageView = new ImageView (this); imageView. setBackgroundResource (I); imageList. add (imageView); // you can specify ImageView point = new ImageView (this); LinearLayout. layoutParams params = new LinearLayout. layoutParams (5, 5); params. rightMargin = 20; point. setLayoutParams (params); point. setBackgroundResource (R. drawable. point_bg); if (I = R. drawable. a) {point. setEnabled (true);} else {point. setEnabled (false);} point_group.addView (point);} viewPager. setAdapter (new MyPageAdapter (); // you can specify the position of the current viewPager. setCurrentItem (Integer. MAX_VALUE/2-(Integer. MAX_VALUE/2% imageList. size (); viewPager. setOnPageChangeListener (new OnPageChangeListener () {@ Overridepublic void onPageSelected (int position) {// called after page switching, position is the new page position // implement unrestricted loop playback position % = imageList. size (); image_desc.setText (imageDescriptions [position]); // set the current vertex to true and set the previous vertex to falsepoint_group.getChildAt (position ). setEnabled (true); point_group.getChildAt (lastPosition ). setEnabled (false); lastPosition = position ;}@ Overridepublic void onPageScrolled (int position, float positionOffset, int positionOffsetPixels) {// sliding time callback} @ Overridepublic void onPageScrollStateChanged (int state) {// callback when the pageView status changes});/*** Automatic loop: 1. timer: Timer 2. enable sub-thread: while true loop 3. clockManger * 4. use Handler to send delayed messages to achieve loop, which is the simplest and most convenient **/handler. sendEmptyMessageDelayed (0, 2000) ;}@ Overrideprotected void onDestroy () {// stop rolling isRunning = false; super. onDestroy ();} private class MyPageAdapter extends PagerAdapter {// you need to implement the following four methods @ Overridepublic int getCount () {// get the total number of pages return Integer. MAX_VALUE ;}@ Overridepublic boolean isViewFromObject (View view, Object object) {// determine whether the view and Object are correlated. if (view = object) {return true ;} else {return false ;}@ Overridepublic Object instantiateItem (ViewGroup container, int position) {// obtain the view at the corresponding position; the container of the container view is actually the viewpage itself, // position: position on viewpager // Add content container to the container. addView (imageList. get (position % imageList. size (); return imageList. get (position % imageList. size () ;}@ Overridepublic void destroyItem (ViewGroup container, int position, Object object) {// destroy the Object at the corresponding position // super. destroyItem (container, position, object); container. removeView (View) object); object = null ;}}}

The effect is as follows:




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.