ViewPager + handler implement carousel and viewpagerhandler

Source: Internet
Author: User

ViewPager + handler implement carousel and viewpagerhandler

Let's talk about the next function. Set a set of network image links as image resources. I use ImageLoader to load images. The progress bar is loaded when the images are not loaded.

Send an empty message in Handler to implement page carousel

The following is the code. I wrote it in a class and observed it.

Package com. demo. sb. main; import com. demo. suibian. r; import com. nostra13.universalimageloader. core. displayImageOptions; import com. nostra13.universalimageloader. core. imageLoader; import com. nostra13.universalimageloader. core. assist. failReason; import com. nostra13.universalimageloader. core. assist. imageScaleType; import com. nostra13.universalimageloader. core. display. fadeInBitmapDisplayer; import com. nostra13.universalimageloader. core. listener. simpleImageLoadingListener; import android. app. activity; import android. graphics. bitmap; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. support. v4.view. pagerAdapter; import android. support. v4.view. viewPager; import android. support. v4.view. viewPager. onPageChangeListener; import android. util. log; import android. view. motionEvent; import android. view. view; import android. view. view. onTouchListener; import android. view. viewTreeObserver. onGlobalLayoutListener; import android. view. viewGroup; import android. widget. imageView; import android. widget. imageView. scaleType; import android. widget. linearLayout; import android. widget. progressBar; import android. widget. relativeLayout; public class Activity_Other extends Activity {private ViewPager viewPager; private ImageLoader loader; private DisplayImageOptions options; // private static final int [] mImageIds = new int [] {R. drawable. guide_1, // R. drawable. guide_2, R. drawable. guide_3}; // picture resource public static final String [] IMAGES = new String [] {"http://image.tianjimedia.com/uploadImages/2012/067/ORQR14KR5DDC.jpg", "http://image.tianjimedia.com/uploadImages/2012/067/X6BEO07U962E.jpg", "http://image.tianjimedia.com/uploadImages/2012/067/F9X84V2ST716.jpg", "http://image.tianjimedia.com/uploadImages/2012/067/RY445ENQ16BH.jpg ", "http://image.tianjimedia.com/uploadImages/2012/067/74KAJLN0JL95.jpg", "http://image.tianjimedia.com/uploadImages/2012/067/N80N0GUA36N0.jpg"}; // private ArrayList <ImageView> mImageViewList; private LinearLayout llPointGroup; // parent control of the guiding dot private int mPointWidth; // The distance between the dots is private View viewRedPoint; // /// private Handler mhandler; private Handler mhandler = new Handler () {public void handleMessage (Message msg) {int currentItem = viewPager. getCurrentItem (); if (currentItem <IMAGES. length-1) {currentItem ++;} else {currentItem = 0;} viewPager. setCurrentItem (currentItem); // switch to mhandler on the next page. sendEmptyMessageDelayed (0, 3000); // send a message with a 3-second delay until the Handler continues to execute to form a loop} ;};@ Override protected void onCreate (Bundle savedInstanceState) {// TODO Auto-generated method stub super. onCreate (savedInstanceState); setContentView (R. layout. activity_other); loader = ImageLoader. getInstance (); options = new DisplayImageOptions. builder (). showImageForEmptyUri (R. drawable. ic_empty ). showImageOnFail (R. drawable. ic_error ). resetViewBeforeLoading (true ). cacheOnDisc (false ). cacheInMemory (true ). imageScaleType (ImageScaleType. EXACTLY ). bitmapConfig (Bitmap. config. RGB_565 ). displayers (new FadeInBitmapDisplayer (300 )). build (); viewPager = (ViewPager) findViewById (R. id. viewpager1); llPointGroup = (LinearLayout) findViewById (R. id. ll_point_group); viewRedPoint = findViewById (R. id. view_red_point); initViews (); viewPager. setAdapter (new GuideAdapter (); viewPager. setOnPageChangeListener (new GuidePageListener (); mhandler. sendEmptyMessageDelayed (0, 3000); // send a message after a delay of 3 seconds for handler to achieve carousel} private void initViews () {// TODO Auto-generated method stub // mImageViewList = new ArrayList <ImageView> (); /////// initialize the three pages of the boot page // for (int I = 0; I <mImageIds. length; I ++) {// ImageView image = new ImageView (this); // image. setBackgroundResource (mImageIds [I]); // sets the background of the boot page // mImageViewList. add (image); //} for (int I = 0; I <IMAGES. length; I ++) {View point = new View (this); point. setBackgroundResource (R. drawable. point_normal); // set the default point of the boot page. setPadding (5, 5, 5, 5); LinearLayout. layoutParams params = new LinearLayout. layoutParams (10, 10); if (I> 0) {params. leftMargin = 10; // set the dot interval} point. setLayoutParams (params); // sets the llPointGroup of the dot size. addView (point); // Add the dot to the linear layout} // obtain the view tree and listen to the llPointGroup for the layout end event. getViewTreeObserver (). addOnGlobalLayoutListener (new OnGlobalLayoutListener () {// call back this method after layout execution ends @ Override public void onGlobalLayout () {System. out. println ("layout ended"); llPointGroup. getViewTreeObserver (). removeGlobalOnLayoutListener (this); mPointWidth = llPointGroup. getChildAt (1 ). getLeft ()-llPointGroup. getChildAt (0 ). getLeft (); System. out. println ("dot distance:" + mPointWidth );}});} /*** touch listening: Do not carousel when pressed ** @ author Administrator **/class NewTouchListener implements OnTouchListener {@ Override public boolean onTouch (View arg0, MotionEvent arg1) {switch (arg1.getAction () {case MotionEvent. ACTION_DOWN: System. out. println ("pressed"); mhandler. removeCallbacksAndMessages (null); break; case MotionEvent. ACTION_CANCEL: System. out. println ("event canceled"); mhandler. sendEmptyMessageDelayed (0, 3000); break; case MotionEvent. ACTION_UP: System. out. println ("lifted"); mhandler. sendEmptyMessageDelayed (0, 3000); break; default: break;} return true ;}} /*** ViewPager data adapter ** @ author Kevin **/class GuideAdapter extends PagerAdapter {@ Override public int getCount () {return IMAGES. length ;}@ Override public boolean isViewFromObject (View arg0, Object arg1) {return arg0 = arg1 ;}@ Override public Object instantiateItem (ViewGroup container, int position) {// ImageView imageView = new ImageView (Activity_Other.this); // imageView. setScaleType (ScaleType. FIT_XY); // loader. displayImage (IMAGES [position], imageView, options); // container. addView (imageView); // imageView. setOnTouchListener (new NewTouchListener (); // return imageView; View imageLayout = View. inflate (Activity_Other.this, R. layout. item_pager_image, null); ImageView imageView = (ImageView) imageLayout. findViewById (R. id. image); imageView. setScaleType (ScaleType. FIT_XY); ProgressBar spinBar = (ProgressBar) imageLayout. findViewById (R. id. loading); loader. displayImage (IMAGES [position], imageView, options, new MySimpleLoading (spinBar); container. addView (imageLayout); imageView. setOnTouchListener (new NewTouchListener (); return imageLayout;} @ Override public void destroyItem (ViewGroup container, int position, Object object Object) {container. removeView (View) object);} class MySimpleLoading extends SimpleImageLoadingListener {ProgressBar spinBar; public MySimpleLoading (ProgressBar spinBar) {// TODO Auto-generated constructor stub this. spinBar = spinBar;} // start loading @ Override public void onLoadingStarted (String imageUri, View view) {// TODO Auto-generated method stub spinBar. setVisibility (View. VISIBLE);} // loading failed @ Override public void onLoadingFailed (String imageUri, View view, FailReason failReason) {// TODO Auto-generated method stub String message = null; switch (failReason. getType () {case IO_ERROR: message = "Input/Output error"; break; case DECODING_ERROR: message = "Image can't be decoded"; break; networkcase _denied: message = "Downloads are denied"; break; case OUT_OF_MEMORY: message = "Out Of Memory error"; break; case UNKNOWN: message = "Unknown error"; break;} Log. I ("ImagePagerAdapter", message); spinBar. setVisibility (View. GONE);} // @ Override public void onLoadingComplete (String imageUri, View view, Bitmap loadedImage) {// TODO Auto-generated method stub spinBar. setVisibility (View. GONE) ;}}/*** sliding listener for viewpager ** @ author Kevin **/class GuidePageListener implements OnPageChangeListener {// sliding event @ Override public void onPageScrolled (int position, float positionOffset, int positionOffsetPixels) {// System. out. println ("Current position:" + position + "; percentage:" + positionOffset // + "; moving distance:" + positionOffsetPixels); int len = (int) (mPointWidth * positionOffset) + position * mPointWidth; RelativeLayout. layoutParams params = (RelativeLayout. layoutParams) viewRedPoint. getLayoutParams (); // get the layout parameter params of the current red point. leftMargin = len; // set the left-side distance from viewRedPoint. setLayoutParams (params); // set the layout parameter for the red dot again} // a page is selected @ Override public void onPageSelected (int position) {}// sliding status changed @ Override public void onPageScrollStateChanged (int state ){}}}
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <RelativeLayout        android:layout_width="match_parent"        android:id="@+id/rl_root"        android:layout_height="200dp" >        <android.support.v4.view.ViewPager            android:id="@+id/viewpager1"            android:layout_width="match_parent"            android:layout_height="match_parent" />        <RelativeLayout            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_alignParentBottom="true"            android:layout_centerHorizontal="true"            android:layout_marginBottom="20dp" >            <LinearLayout                android:id="@+id/ll_point_group"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:orientation="horizontal" >            </LinearLayout>            <View                android:id="@+id/view_red_point"                android:layout_width="8dp"                android:layout_height="8dp"                android:background="@drawable/point_selecte" />        </RelativeLayout>    </RelativeLayout>    <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="@string/app_name" /></LinearLayout>
<?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:padding="1dip" >    <ImageView        android:id="@+id/image"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_gravity="center"        android:adjustViewBounds="true"        android:contentDescription="@null"        android:scaleType="fitXY" />    <ProgressBar        android:id="@+id/loading"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center"        android:visibility="gone" /></FrameLayout>

 

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.