Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> ViewPager+handler實現輪播,viewpagerhandler

ViewPager+handler實現輪播,viewpagerhandler

編輯:關於android開發

ViewPager+handler實現輪播,viewpagerhandler


先說下功能吧,隨便設置一個網絡圖片鏈接的集合,作為圖片的資源。我用ImageLoader來加載圖片,在圖片未加載完成時會ProgressBar加載狀態

在Handler發送一個空消息來實現頁面的輪播

我如下是代碼我寫在一個類中方面觀察

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
    // private static final int[] mImageIds = new int[] { R.drawable.guide_1,
    // R.drawable.guide_2, R.drawable.guide_3 };

    // 網上的圖片資源
    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;// 引導圓點的父控件

    private int mPointWidth;// 圓點間的距離

    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);// 切換到下個頁面
            mhandler.sendEmptyMessageDelayed(0, 3000);//繼續延遲3秒發送消息讓Handler繼續執行 形成循環
        };
    };

    @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)
                .displayer(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);// 延時3秒後發送消息讓handler來實現輪播
    }

    private void initViews() {
        // TODO Auto-generated method stub
        // mImageViewList = new ArrayList<ImageView>();
        //
        // // // 初始化引導頁的3個頁面
        // for (int i = 0; i < mImageIds.length; i++) {
        // ImageView image = new ImageView(this);
        // image.setBackgroundResource(mImageIds[i]);// 設置引導頁背景
        // mImageViewList.add(image);
        // }
        for (int i = 0; i < IMAGES.length; i++) {
            View point = new View(this);
            point.setBackgroundResource(R.drawable.point_normal);// 設置引導頁默認圓點
            point.setPadding(5, 5, 5, 5);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    10, 10);
            if (i > 0) {
                params.leftMargin = 10;// 設置圓點間隔
            }

            point.setLayoutParams(params);// 設置圓點的大小

            llPointGroup.addView(point);// 將圓點添加給線性布局
        }

        // 獲取視圖樹, 對layout結束事件進行監聽
        llPointGroup.getViewTreeObserver().addOnGlobalLayoutListener(
                new OnGlobalLayoutListener() {

                    // 當layout執行結束後回調此方法
                    @Override
                    public void onGlobalLayout() {
                        System.out.println("layout 結束");
                        llPointGroup.getViewTreeObserver()
                                .removeGlobalOnLayoutListener(this);
                        mPointWidth = llPointGroup.getChildAt(1).getLeft()
                                - llPointGroup.getChildAt(0).getLeft();
                        System.out.println("圓點距離:" + mPointWidth);
                    }
                });

    }

    /**
     * 觸摸監聽 當按下時不進行輪播
     * 
     * @author Administrator
     * 
     */
    class NewTouchListener implements OnTouchListener {

        @Override
        public boolean onTouch(View arg0, MotionEvent arg1) {
            switch (arg1.getAction()) {
            case MotionEvent.ACTION_DOWN:
                System.out.println("按下了");
                mhandler.removeCallbacksAndMessages(null);
                break;
            case MotionEvent.ACTION_CANCEL:
                System.out.println("事件取消");
                mhandler.sendEmptyMessageDelayed(0, 3000);
                break;
            case MotionEvent.ACTION_UP:
                System.out.println("抬起");
                mhandler.sendEmptyMessageDelayed(0, 3000);
                break;
            default:
                break;
            }
            return true;
        }

    }

    /**
     * ViewPager數據適配器
     * 
     * @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) {
            container.removeView((View) object);
        }
    }

    class MySimpleLoading extends SimpleImageLoadingListener {
        ProgressBar spinBar;

        public MySimpleLoading(ProgressBar spinBar) {
            // TODO Auto-generated constructor stub
            this.spinBar = spinBar;
        }
        //開始加載
        @Override
        public void onLoadingStarted(String imageUri, View view) {
            // TODO Auto-generated method stub
            spinBar.setVisibility(View.VISIBLE);
        }
        //加載失敗
        @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;
            case NETWORK_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);
        }

    }

    /**
     * viewpager的滑動監聽
     * 
     * @author Kevin
     * 
     */
    class GuidePageListener implements OnPageChangeListener {

        // 滑動事件
        @Override
        public void onPageScrolled(int position, float positionOffset,
                int positionOffsetPixels) {
            // System.out.println("當前位置:" + position + ";百分比:" + positionOffset
            // + ";移動距離:" + positionOffsetPixels);
            int len = (int) (mPointWidth * positionOffset) + position
                    * mPointWidth;
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewRedPoint
                    .getLayoutParams();// 獲取當前紅點的布局參數
            params.leftMargin = len;// 設置左邊距

            viewRedPoint.setLayoutParams(params);// 重新給小紅點設置布局參數
        }

        // 某個頁面被選中
        @Override
        public void onPageSelected(int position) {

        }

        // 滑動狀態發生變化
        @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>

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved