Banner

利用** ViewPager **实现广告 Banner 循环轮播。




    
    
    
        
        

        

        

        

        
    

package com.ttt.bannertest;

import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {

    private ViewPager viewPager;
    private List imageViewList;
    private List dotList;
    private int currentItem;
    private ScheduledExecutorService scheduledExecutorService;
    private Boolean isAutoPlay=false;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            viewPager.setCurrentItem(currentItem);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        currentItem=0;
        initImageList();
        initDotList();
        viewPager=(ViewPager)findViewById(R.id.view_pager);
        viewPager.setAdapter(new PagerAdapter() {
            @Override
            public int getCount() {
                return imageViewList.size();
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view==object;
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                container.addView(imageViewList.get(position));
                return imageViewList.get(position);
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView(imageViewList.get(position));
            }
        });
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                currentItem=position;
                for(int i=0;i<5;i++){
                    if(i==position){
                        dotList.get(i).setBackgroundResource(R.drawable.dot_focus);
                    }else {
                        dotList.get(i).setBackgroundResource(R.drawable.dot_normal);
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                switch (state){
                    case 0:
                        if(!isAutoPlay){
                            startPlay();
                            isAutoPlay=true;
                        }
                        break;
                    case 1:
                        stopPlay();
                        isAutoPlay=false;
                        break;
                    default:
                        break;
                }
            }
        });
    }

    private void initImageList(){
        imageViewList=new ArrayList<>();
        for(int i=0;i<5;i++){
            ImageView imageView=new ImageView(this);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            Glide.with(this).load("http://p2.zhimg.com/9a/15/9a1570bb9e5fa53ae9fb9269a56ee019.jpg")
                    .into(imageView);
            imageViewList.add(imageView);
        }
    }

    private void initDotList(){
        dotList=new ArrayList<>();
        dotList.add(findViewById(R.id.dot_1));
        dotList.add(findViewById(R.id.dot_2));
        dotList.add(findViewById(R.id.dot_3));
        dotList.add(findViewById(R.id.dot_4));
        dotList.add(findViewById(R.id.dot_5));
    }

    // 创建单线程化的线程池,并延时发送 message 来不断切换 ViewPager 的 item。
    private void startPlay(){
        scheduledExecutorService=Executors.newSingleThreadScheduledExecutor();
        // 开启后第一次延时 2 s,周期 5 s,执行 SlideTask 任务。
        scheduledExecutorService.scheduleAtFixedRate(new SlideTask(),2,5, TimeUnit.SECONDS);
        isAutoPlay=true;
    }

    private void stopPlay(){
        scheduledExecutorService.shutdown();
    }

    // 后台时停止播放。
    @Override
    protected void onStop() {
        stopPlay();
        isAutoPlay=false;
        super.onStop();
    }

    @Override
    protected void onStart() {
        super.onStart();
        startPlay();
        isAutoPlay=true;
    }

    private class SlideTask implements Runnable{

        @Override
        public void run() {
            synchronized (viewPager){
                currentItem=(currentItem+1)%imageViewList.size();
                handler.obtainMessage().sendToTarget();
            }
        }
    }
}

你可能感兴趣的:(Banner)