android轮播图示例

首先轮播图使用ViewPager控件来播放,如果有不懂ViewPager可以先去了解一下,可以看看我之前写的http://blog.csdn.net/ksj_j/article/details/53588080

首先说一下我们要实现的功能有图片可以滑动轮播,可以自动轮播,还有标记显示图片处于第几张图片的圆点


效果图如下



activity_main.xml



    
	 
	
	    
	    
	    
    
    


MainActivity.java

package com.example.viewpager;



import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ActivityManager.RunningAppProcessInfo;
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.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

public class MainActivity extends Activity {

	private ViewPager vp;
	private LinearLayout ll;
	private ImageView iv;
        //每次圆点移动的位移
       private int move;
        //图片资源
       private int[] image =new int[]{R.drawable.iv1,R.drawable.iv2,
			R.drawable.iv3,R.drawable.iv4,R.drawable.iv5};
	private List imagelist;
        判断是否需要自动播放
       private boolean running = true;
        //实现自动播放
       private Handler handler = new Handler(){
		//每隔5秒自动实现vp的position加1
		public void handleMessage(Message msg) {
			vp.setCurrentItem(vp.getCurrentItem()+1);
			System.out.println(vp.getCurrentItem());
			if(running){
				handler.sendEmptyMessageDelayed(0, 3000);
			}
		};
	};
	@Override
	protected void onDestroy() {
		running = false;
        super.onDestroy();
	};
	
	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();
		//handler.sendEmptyMessage(1);
		for(int i = 0; i < image.length; i ++){
			ImageView imageView = new ImageView(this);
			imageView.setImageResource(image[i]);
			imageView.setScaleType(ScaleType.FIT_XY);
			imagelist.add(imageView);
			//根据图片的个数去放置相应数量的圆点3
			ImageView imageView2 = new ImageView(this);
			imageView2.setImageResource(R.drawable.circle);
                        //因为没有直接改变margin的方法,所以这里使用的LayoutParams来改变leftMargin
                       LinearLayout.LayoutParams  layoutParams = new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
			if(i > 0){
				layoutParams.leftMargin = 20;
			}
			imageView2.setLayoutParams(layoutParams);

			ll.addView(imageView2);
			
		}
		//布局加载完成节后运行
		iv.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
			
			@Override
			public void onGlobalLayout() {
				// TODO Auto-generated method stub
				//内部子空间的距离获取
				move = ll.getChildAt(1).getLeft()-ll.getChildAt(0).getLeft();
			}
		});
		//添加监听时间
		vp.setOnPageChangeListener(new OnPageChangeListener() {
			
			
			@Override
			public void onPageSelected(int arg0) {
				// TODO Auto-generated method stub
				
			}
			
			
			//滑动界面触发,这里控制标记点的改变就可以了
			//position第几幅图,offset滑动百分比
			@Override
			public void onPageScrolled(int position, float offset, int arg2) {
				// TODO Auto-generated method stub
				System.out.println(position);
				RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)iv.getLayoutParams();
				if((position+1)%image.length != 0)
					layoutParams.leftMargin = (int)((position%image.length)*move+offset*move);
				iv.setLayoutParams(layoutParams);
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		//添加适配器
		//vp.setPageTransformer(true, arg1);
		vp.setAdapter(new PagerAdapter() {
		
			@Override
			public Object instantiateItem(ViewGroup container, int position) {
				// TODO Auto-generated method stub
				
				container.addView(imagelist.get((position+image.length)%(image.length)));
				//返回滑动到的图片
				return imagelist.get((position+image.length)%(image.length));
			}
			
			@Override
			public void destroyItem(ViewGroup container, int position, Object object) {
				// TODO Auto-generated method stub
                                //移除一张前图片
                               container.removeView(imagelist.get((position+image.length)%(image.length)));
			}
			
			@Override
			public boolean isViewFromObject(View arg0, Object arg1) {
				// TODO Auto-generated method stub
				return arg0 == arg1;
			}
			//使得ViewPager可以无限移动,设置边界为Integer.MAX_VALUE
			@Override
			public int getCount() {
				// TODO Auto-generated method stub
				return Integer.MAX_VALUE;
			}
		});
		
		//插入切换样式,这个随便一个地方拷贝一份即可,可以到官方拷贝
		vp.setPageTransformer(true, new DepthPageTransformer());

        handler.sendEmptyMessageDelayed(0, 3000);
	}
	
	private void initView() {
		// TODO Auto-generated method stub
		ll = (LinearLayout)findViewById(R.id.ll);
		vp = (ViewPager)findViewById(R.id.vp);
		iv = (ImageView)findViewById(R.id.iv);
		imagelist = new ArrayList<>();
	}
		
	
}


圆点设计:圆点表示第几幅图

circle.xml



    
    



circle_bg.xml



    
    
    



改变切换图样式代码

DepthPageTransformer.java

package com.example.viewpager;

import android.annotation.SuppressLint;
import android.support.v4.view.ViewPager.PageTransformer;
import android.view.View;


public class DepthPageTransformer implements PageTransformer {
    private static final float MIN_SCALE = 0.75f;

    @SuppressLint("NewApi")
	public void transformPage(View view, float position) {
        int pageWidth = view.getWidth();

        if (position < -1) { // [-Infinity,-1)
            // This page is way off-screen to the left.
            view.setAlpha(0);

        } else if (position <= 0) { // [-1,0]
            // Use the default slide transition when moving to the left page
            view.setAlpha(1);
            view.setTranslationX(0);
            view.setScaleX(1);
            view.setScaleY(1);

        } else if (position <= 1) { // (0,1]
            // Fade the page out.
            view.setAlpha(1 - position);

            // Counteract the default slide transition
            view.setTranslationX(pageWidth * -position);

            // Scale the page down (between MIN_SCALE and 1)
            float scaleFactor = MIN_SCALE
                    + (1 - MIN_SCALE) * (1 - Math.abs(position));
            view.setScaleX(scaleFactor);
            view.setScaleY(scaleFactor);

        } else { // (1,+Infinity]
            // This page is way off-screen to the right.
            view.setAlpha(0);
        }
    }
}

总结:首先我使用的是ViewPager实现轮播图,继承PagerAdapter重写方法实现图片的切换,实现接口OnPageChangeListener监听可以来动态改变圆点的位子,接下来实现轮播图自动播放

自动循环: 1.定时器:Timer 2.开子线程:while true循环 3.ClockManger 4.用Handler发送延时信息,实现循环,最简单最方便

这里我使用Handler来实现自动循环

你可能感兴趣的:(android)