使用ViewPager实现可以自动切换的广告控件

在android应用开发中,经常会用到Banner控件,作为一些活动和运营的预留位置,这种Banner控件可以使用ViewPager来实现。


Banner类的实现:

public class CommonBannerView extends RelativeLayout {

    private ImageView[] imageViews = null;
    private ImageView imageView = null;
    private ViewPager advPager = null;
    private AtomicInteger what = new AtomicInteger(0);
    private boolean isContinue = true;
    private Context mContext;
    private ViewGroup mGroup;
    private int mCurrentIndex;

    private float mTouchDownX = 0;
    private float mTouchDownY = 0;

    private int mCount = 0;

    public CommonBannerView(Context context) {
        super(context);
        mContext = context;
        init();
    }

    public CommonBannerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mContext = context;
        init();
    }

    public CommonBannerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        init();
    }

    private void init(){
        LayoutInflater.from(mContext).inflate(R.layout.layer_common_banner_view, this);
        advPager = (ViewPager) findViewById(R.id.adv_pager);
        mGroup = (ViewGroup) findViewById(R.id.viewGroup);
    }

    public void setData(){

        int[] res = {R.drawable.banner0 , R.drawable.banner1 , R.drawable.banner2};
        int count = res.length;
        List<View> advPics = new ArrayList<View>();
        for(int i = 0 ; i < count ; i ++){
            ImageView img = new ImageView(mContext);
            img.setImageResource(res[i]);
            img.setScaleType(ImageView.ScaleType.FIT_XY);
            advPics.add(img);
        }

        //指示banner个数及选中状态的圆点
        imageViews = new ImageView[advPics.size()];
        for (int i = 0; i < advPics.size(); i++) {
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new LayoutParams(20, 20));
            imageView.setPadding(5, 5, 5, 5);
            imageViews[i] = imageView;
            if (i == 0) {
                imageViews[i]
                        .setBackgroundResource(R.drawable.ic_banner_selected);
            } else {
                imageViews[i]
                        .setBackgroundResource(R.drawable.ic_banner_nor);
            }
            mGroup.addView(imageViews[i]);
        }

        mCurrentIndex = 0;

        advPager.setAdapter(new AdvAdapter(advPics));

        advPager.setOnPageChangeListener(new GuidePageChangeListener());
        advPager.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        isContinue = false;
                        removeMessage();
                        mTouchDownX = event.getX();
                        mTouchDownY = event.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        isContinue = false;
                        break;
                    case MotionEvent.ACTION_UP:
                        //如果水平和竖直方向的移动距离均小于五个像素则视为点击事件
                        if (Math.abs(event.getX() - mTouchDownX) < 5 && Math.abs(event.getY() - mTouchDownY) < 5) {
				//处理点击事件
                        }
                        mTouchDownX = 0;
                        mTouchDownY = 0;
                        isContinue = true;
                        viewHandler.sendEmptyMessageDelayed(0, 5000);
                        break;
                    default:
                        isContinue = true;
                        break;
                }
                return false;
            }
        });
    }

    public void start(){
        viewHandler.sendEmptyMessageDelayed(0 , 5000);
    }

    private final class GuidePageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrollStateChanged(int arg0) {

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {

        }

        @Override
        public void onPageSelected(int arg0) {
            what.getAndSet(arg0);
            mCurrentIndex = arg0;
            mCount = arg0;
            for (int i = 0; i < imageViews.length; i++) {
                imageViews[arg0]
                        .setBackgroundResource(R.drawable.ic_banner_selected);
                if (arg0 != i) {
                    imageViews[i]
                            .setBackgroundResource(R.drawable.ic_banner_nor);
                }
            }

        }

    }

    public void removeMessage(){
        viewHandler.removeCallbacksAndMessages(null);
    }

    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) {

        }
    }

    private final Handler viewHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if(imageViews != null && imageViews.length != 0) {
                mCount ++;
                mCount %= imageViews.length;
                advPager.setCurrentItem(mCount);
            }
            viewHandler.sendEmptyMessageDelayed(0, 5000);
            super.handleMessage(msg);
        }

    };
}
 
XML文件:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <android.support.v4.view.ViewPager
        android:id="@+id/adv_pager"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

    <LinearLayout
        android:id="@+id/viewGroup"
        android:layout_below="@id/adv_pager"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="-25px"
        android:gravity="center"
        android:orientation="horizontal" >
    </LinearLayout>
</merge>
调用:
public class MainActivity extends ActionBarActivity {

    private CommonBannerView mBannerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mBannerView = (CommonBannerView) findViewById(R.id.banner_view);
        mBannerView.setData();
        mBannerView.start();
    }


    //防止内存泄露或者下次进入时出现多个message的情况
    @Override
    protected void onPause() {
        super.onPause();
        mBannerView.removeMessage();
    }
}
MainActivity的布局文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <com.dafasoft.bannertest.CommonBannerView
        android:id="@+id/banner_view"
        android:layout_width="fill_parent"
        android:layout_height="200dp"/>

</RelativeLayout>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值