Android:用ViewPager实现广告栏

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

技术分享


技术分享

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


1、布局文件 layout_ad_pager.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="160dp"
    android:baselineAligned="false" >

    <ImageView
        android:id="@+id/home_default_image"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:scaleType="fitXY"
        android:src="@drawable/home_log_default"
        android:visibility="gone" />

    <android.support.v4.view.ViewPager
        android:id="@+id/adv_pager"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/img2" >
    </android.support.v4.view.ViewPager>

    <LinearLayout
        android:id="@+id/viewGroup"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal|bottom"
        android:layout_marginBottom="5dp"
        android:gravity="center"
        android:orientation="horizontal" >
    </LinearLayout>

</FrameLayout>

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<View> 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<View>();
    }
    
    /**
     * 初始化控件
     */
    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<View> views = null;
        
        public AdvAdapter(List<View> 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) {
            
        }
    }
}

图片资源:

技术分享 

技术分享







郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。