Android:用ViewPager实现广告栏

现在常见的广告栏效果,自动切换广告,也可手动滑动切换。

Android:用ViewPager实现广告栏_第1张图片


Android:用ViewPager实现广告栏_第2张图片

我用ViewPager实现的,废话不多说,上代码:


1、布局文件 layout_ad_pager.xml




    

    
    

    
    


2、主要代码 AdPagerMainActivity.java

package app.adpager;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class AdPagerMainActivity extends ActionBarActivity {
    
    private ImageView mDefaultImage = null;
    
    private ViewPager mImagePager = null;
    
    private ImageView[] mImageViews = null;
    
    private AtomicInteger what = new AtomicInteger(0);
    
    private boolean isContinue = true;
    
    private List advPics;
    
    private Context mContext;
    
    private ImageView mImageView;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.layout_ad_pager);
        init();
        initView();
        initViewPager();
    }
    
    /**
     * 初始化数据
     */
    private void init() {
        mContext = this;
        advPics = new ArrayList();
    }
    
    /**
     * 初始化控件
     */
    private void initView() {
        // TODO Auto-generated method stub
        mDefaultImage = (ImageView) findViewById(R.id.home_default_image);
        mImagePager = (ViewPager) findViewById(R.id.adv_pager);
    }
    
    /**
     * void
     */
    private void initViewPager() {
        // TODO Auto-generated method stub
        mDefaultImage.setVisibility(View.GONE);
        mImagePager.setVisibility(View.VISIBLE);
        
        ImageView img1 = new ImageView(mContext);
        img1.setBackgroundResource(R.drawable.img1);
        advPics.add(img1);
        
        ImageView img2 = new ImageView(mContext);
        img2.setBackgroundResource(R.drawable.img2);
        advPics.add(img2);
        
        ImageView img3 = new ImageView(mContext);
        img3.setBackgroundResource(R.drawable.img3);
        advPics.add(img3);
        
        ImageView img4 = new ImageView(mContext);
        img4.setBackgroundResource(R.drawable.img4);
        advPics.add(img4);
        
        // group是R.layou.mainview中的负责包裹小圆点的LinearLayout.
        ViewGroup group = (ViewGroup) findViewById(R.id.viewGroup);
        mImageViews = new ImageView[advPics.size()];
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(13, 13);
        layoutParams.setMargins(5, 0, 5, 1);
        
        for (int i = 0; i < advPics.size(); i++) {
            mImageView = new ImageView(this);
            mImageView.setLayoutParams(layoutParams);
            mImageViews[i] = mImageView;
            if (i == 0) {
                // 默认选中第一张图片
                mImageViews[i].setBackgroundResource(R.drawable.item_focus);
            }
            else {
                mImageViews[i].setBackgroundResource(R.drawable.item_unfocus);
            }
            group.addView(mImageViews[i]);
        }
        
        mImagePager.setAdapter(new AdvAdapter(advPics));
        mImagePager.setOnPageChangeListener(new GuidePageChangeListener());
        // 按下时不继续定时滑动,弹起时继续定时滑动
        mImagePager.setOnTouchListener(new View.OnTouchListener() {
            
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                    case MotionEvent.ACTION_MOVE:
                        isContinue = false;
                        break;
                    case MotionEvent.ACTION_UP:
                        isContinue = true;
                        break;
                    default:
                        isContinue = true;
                        break;
                }
                return false;
            }
        });
        // 定时滑动线程
        new Thread(new Runnable() {
            
            @Override
            public void run() {
                while (true) {
                    if (isContinue) {
                        viewHandler.sendEmptyMessage(what.get());
                        whatOption();
                    }
                }
            }
            
        }).start();
    }
    
    /**
     * 操作圆点轮换变背景
     */
    private void whatOption() {
        what.incrementAndGet();
        if (what.get() > mImageViews.length - 1) {
            what.getAndAdd(-mImageViews.length);
        }
        try {
            if (what.get() == 1) {
                Thread.sleep(3000);
            }
            else {
                Thread.sleep(2000);
            }
        }
        catch (InterruptedException e) {
        }
    }
    
    /**
     * 处理定时切换广告栏图片的句柄
     */
    @SuppressLint("HandlerLeak")
    private final Handler viewHandler = new Handler() {
        
        @Override
        public void handleMessage(Message msg) {
            mImagePager.setCurrentItem(msg.what);
            super.handleMessage(msg);
        }
    };
    
    /** 指引页面改监听器 */
    private final class GuidePageChangeListener implements OnPageChangeListener {
        
        @Override
        public void onPageScrollStateChanged(int arg0) {
            
        }
        
        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            
        }
        
        @Override
        public void onPageSelected(int arg0) {
            arg0 = arg0 % advPics.size();
            for (int i = 0; i < mImageViews.length; i++) {
                mImageViews[arg0].setBackgroundResource(R.drawable.item_focus);
                if (arg0 != i) {
                    mImageViews[i].setBackgroundResource(R.drawable.item_unfocus);
                }
            }
            what.set(arg0);
        }
    }
    
    /**
     * @Description: 广告栏PaperView 图片适配器
     */
    private final class AdvAdapter extends PagerAdapter {
        private List views = null;
        
        public AdvAdapter(List views) {
            this.views = views;
        }
        
        @Override
        public void destroyItem(View arg0, int arg1, Object arg2) {
            ((ViewPager) arg0).removeView(views.get(arg1));
        }
        
        @Override
        public void finishUpdate(View arg0) {
            
        }
        
        @Override
        public int getCount() {
            return views.size();
        }
        
        @Override
        public Object instantiateItem(View arg0, int arg1) {
            ((ViewPager) arg0).addView(views.get(arg1), 0);
            return views.get(arg1);
        }
        
        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }
        
        @Override
        public void restoreState(Parcelable arg0, ClassLoader arg1) {
            
        }
        
        @Override
        public Parcelable saveState() {
            return null;
        }
        
        @Override
        public void startUpdate(View arg0) {
            
        }
    }
}

图片资源:

 








你可能感兴趣的:(Android)