android轮播图的实现

轮播图是通过ViewPager实现,轮播效果在子线程中通过handler机制设置viewPager显示的Item

public class HomeScrollViewFragment extends Fragment {
//这里使用的是ScrollView组件,配合Fragment

    private ObservableScrollView mScrollView;
    private View mView;
    private ViewPager mSlidingShow;
    private MyClickListener mListener;
    private SlidingShowAdapter mSlidingShowAdapter;
    private List<Image> mSlidingImages;
    private BitmapUtils mBitmapUtils;
    private int pointSelectIndex;
//测试用的图片URL
    String imgPaths[]={"http://pic.baike.soso.com/p/20130802/20130802214330-825586008.jpg",
        "http://img03.tooopen.com/uploadfile/downs/images/20110811/sy_20110811170230819021.jpg","http://img.zcool.cn/community/03396a3554c74f700000158fc16b02b.jpg",
        "http://rios.co/wp-content/uploads/2012/11/rioswing_diy_field_02.jpg",
        "http://abc.2008php.com/2012_Website_appreciate/2012-06-24/20120624160018.jpg"

};
    private LinearLayout mLl_ponits;
    private int mPotinIsSelect;
    private SlidingShow mMySliding;

    public static HomeScrollViewFragment newInstance() {
        return new HomeScrollViewFragment();}

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_home_scrollview, container, false);
        initView();
        return mView;
    }

    private void initView() {
     //轮播图findViewByid
        mSlidingShow = (ViewPager) mView.findViewById(R.id.home_slidingShow);
        mBitmapUtils = new BitmapUtils(getActivity().getApplicationContext());
        mBitmapUtils.configDefaultBitmapConfig(Bitmap.Config.ARGB_4444);//设置一个字节的像素
        mLl_ponits = (LinearLayout) mView.findViewById(R.id.ll_home_piont);//轮播图上的点
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mScrollView = (ObservableScrollView) view.findViewById(R.id.scrollView);
        MaterialViewPagerHelper.registerScrollView(getActivity(), mScrollView, null);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mMySliding = new SlidingShow();//创建轮播图类
        setData();//设置数据
        initEvent();//设置事件
    }

/**
这是一个私有内部类,封装了轮播图的功能,该类继承了handler实现了Runnable接口
**/
    private class SlidingShow extends Handler implements Runnable{
    //停止轮播的方法
     public void stopSlidingShow(){
         removeCallbacksAndMessages(null);
     }
     //开始轮播的方法
     public void startSlidingShow(){
         postDelayed(this,5000);
     }

     //轮播的逻辑要放在子线程中实现
    @Override
    public void run() {
        //每隔5秒设置viewPager的当前页面一次   mSlidingShow.setCurrentItem((mSlidingShow.getCurrentItem()+1)%mSlidingShow.getAdapter().getCount());
        postDelayed(this,5000);
    }
}

    //设置数据

    private void setData() {
        setSlidingShowData();
        initPoints();
        setPotinIsSelect(pointSelectIndex);
        mMySliding.startSlidingShow();//开启轮播图
    }
//设置轮播图上的点
    private void initPoints() {
        mLl_ponits.removeAllViews();
        for(int i=0;i<5;i++){
            View v_point=new View(getActivity().getApplicationContext());
            v_point.setBackgroundResource(R.drawable.selector_point);
            v_point.setEnabled(false);//默认都是灰色点
            //设置圆点的半径为5个dip
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(DensityUtils.dipToPx(getActivity(), 5), DensityUtils.dipToPx(getActivity(), 5));
            layoutParams.leftMargin=DensityUtils.dipToPx(getActivity(),10);//将dip转换成px
            v_point.setLayoutParams(layoutParams);
            mLl_ponits.addView(v_point);//将点将在布局上

        }
    }

    /**
     * 轮播图的适配操作
     */
    private void setSlidingShowData() {
        mSlidingShowAdapter = new SlidingShowAdapter();//创建适配器对象
        mSlidingShow.setAdapter(mSlidingShowAdapter);//设置适配器
    }
//设置轮播图上的点是否选中
    public void setPotinIsSelect(int potinIsSelect) {
        for (int i=0;i<5;i++){
            mLl_ponits.getChildAt(i).setEnabled(i==pointSelectIndex);
        }
    }

    /**
     * 轮播图的适配类
     */
private  class SlidingShowAdapter extends PagerAdapter{

        @Override
        public int getCount() {
            return 5;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ImageView iv_SlidingImage=new ImageView(getActivity().getApplicationContext());
//            设置默认图片
            iv_SlidingImage.setImageResource(R.drawable.defualt);
            //给图片添加数据
//            mSlidingShowDatas.get(position);
            //Xutils的BitMap异步加载图片并显示
            mBitmapUtils.display(iv_SlidingImage,imgPaths[position]);
            container.addView(iv_SlidingImage);
//            给图片添加点击事件,在图片轮播的时候,用户按住图片可停止播放松开继续播放
            iv_SlidingImage.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    switch (motionEvent.getAction()){
                        case MotionEvent.ACTION_DOWN://按下
                            mMySliding.stopSlidingShow();
                            break;
                        case MotionEvent.ACTION_UP://松开
                            mMySliding.startSlidingShow();
                            break;
                        case MotionEvent.ACTION_CANCEL://取消
                            mMySliding.startSlidingShow();
                            break;
                        default:
                            break;

                    }
                    return true;
                }
            });
            return iv_SlidingImage;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view==object;
        }
    }
    /**
     * 点击事件
     */
    private void initEvent() {
        //轮播图
        mSlidingShow.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //当滑动到此页面时,设置点被选中
                pointSelectIndex=position;
                setPotinIsSelect(position);

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }
}


public class DensityUtils {
    //根据手机的分辨率将dip转化成px
    public static int dipToPx(Context context,float dpValue){
        float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
        return (int)(scaledDensity*dpValue+0.5f);
    }
    //根据手机的分辨率将px转化成dip
    public static int pxToDip(Context context,float pxValue){
        float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
        return (int)(pxValue/scaledDensity+0.5f);
    }

}


xml

  <android.support.v4.view.ViewPager
                    android:layout_width="match_parent"
                    android:background="@color/left_textView_select"
                    android:id="@+id/home_slidingShow"
                    android:layout_height="@dimen/home_viewpager_height">
                </android.support.v4.view.ViewPager>
                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/ll_home_piont"
                    android:layout_centerHorizontal="true"
                    android:layout_marginTop="144dp"
                    android:orientation="horizontal">
                </LinearLayout>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值