ViewPager+handler实现轮播

先说下功能吧,随便设置一个网络图片链接的集合,作为图片的资源。我用ImageLoader来加载图片,在图片未加载完成时会ProgressBar加载状态

在Handler发送一个空消息来实现页面的轮播

我如下是代码我写在一个类中方面观察

 

补充1  我在scrollview下嵌套ViewPager 会发现VIewPager随便滑动的时候不好使,只有水平方向滑动才行

所以可以自定义MyScrollView

package com.example.huanshop.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ScrollView;

public class MyScrollView extends ScrollView {

    private float xDistance;
    private float yDistance;
    private float xLast;
    private float yLast;

    public MyScrollView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

    public MyScrollView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
    }

    public MyScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
        case MotionEvent.ACTION_DOWN:
            xDistance = yDistance = 0.0f;
            xLast = ev.getX();
            yLast = ev.getY();
            break;
        case MotionEvent.ACTION_MOVE:
            final float curX = ev.getX();
            final float curY = ev.getY();
            xDistance += Math.abs(curX - xLast);
            yDistance += Math.abs(curY - yLast);
            if (xDistance > yDistance)
                return false;
            break;
        default:
            break;
        }
        return super.onInterceptTouchEvent(ev);
    }


}

 补充2  由于屏幕适配的因素而使小点在不同的机子上显示的大小不同达不到想要的效果

可以再用尺寸适配来处理下

    dp和px的关系: dp = px/设备密度
    float density = getResources().getDisplayMetrics().density;
    System.out.println("设备密度:" + density);

    320*240(0.75), 480*320(1),480*800(1.5),1280*720(2)

    values->dimens.xml  values-1280x720

public class DensityUtils {
    /**
     * 将dp转为px
     */
    public static int dp2px(Context ctx, float dp) {
        float density = ctx.getResources().getDisplayMetrics().density;
        int px = (int) (dp * density + 0.5f);// 4.9->5 4.4->4

        return px;
    }

    public static float px2dp(Context ctx, int px) {
        float density = ctx.getResources().getDisplayMetrics().density;
        float dp = px / (density + 0.5f);

        return dp;
    }
}
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    DensityUtils.dp2px(this, 10), DensityUtils.dp2px(this, 10));
            if (i > 0) {
                params.leftMargin = DensityUtils.dp2px(this, 10);// 设置圆点间隔
            }
View Code

 

 

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>

 

其实在android里 if(text ==null || text.length()==0)是有封装的。
在android.text.TextUtils里

public static boolean isEmpty(CharSequence str) {
        if (str == null || str.length() == 0)
            return true;
        else
            return false;
    }
所以我们可以使用
TextUtils.isEmpty(text)

代替

if(text == null || text.length() == 0)

你可能感兴趣的:(ViewPager+handler实现轮播)