ViewPager封装工具类: 轻松实现APP导航或APP中的广告栏

  相信做app应用开发的,绝对都接触过ViewPager,毕竟ViewPager的应用可以说无处不在;APP第一次启动时的新手导航页,APP中结合Fragment实现页面滑动,APP中常见的广告栏的自动滑动(也可手动滑动)。 ViewPager有这么多好处,在APP中到处都可能会用到,那大家岂不是要写好多重复的代码呢? 作为有思想的开发者,我们应当想到,把ViewPager封装起来,做成一个更好使用,更加强大的工具!


  不多说,直接贴代码:

package com.lnyp.viewpagerhelper;

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.widget.ImageView;
import android.widget.LinearLayout;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * ViewPager帮助类,可用于app的引导页,app的广告栏
 **/
public class ViewPagerHelper {
    // 判断是否自动滑动
    private boolean mIsAuto;

    private ViewPager mViewPager;

    private List<View> mViews;

    private LinearLayout mIndicatorParents; // 指示器容器

    private PagerAdapter mPagerAdapter;

    private int mSelect;

    private int mUnSelect;

    private OnViewInstantiateListener mOnViewInstantiateListener;

    // 一个提供原子操作的Integer的类
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    // 广告不停的循环播放
    private boolean isContinue = true;

    /*
     * 每隔固定时间切换广告栏图片
     */
    private final Handler viewHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == mViews.size()) {
                mViewPager.setCurrentItem(1);
            } else {
                mViewPager.setCurrentItem(msg.what);
            }

            super.handleMessage(msg);
        }

    };

    /**
     * View 被附加到viewpager的时候调用
     */
    public interface OnViewInstantiateListener {
        public void onInstantiate(int position, View view);
    }

    /**
     * @param isAuto              指定该ViewPager中的内容是否自动滑动,true为自动滑动,false为手动滑动
     * @param viewPager
     * @param views               加载到ViewPager中的View的集合
     * @param indicatorParents    导航页下面小圆点的父容器
     * @param selectDrawableRes   选中页显示的导航点的图片
     * @param unselectDrawableRes 未选中页的导航点的图片
     */
    public ViewPagerHelper(boolean isAuto, ViewPager viewPager, List<View> views, LinearLayout indicatorParents,
                           int selectDrawableRes, int unselectDrawableRes) {
        mIsAuto = isAuto;
        mViewPager = viewPager;
        mViews = views;
        mIndicatorParents = indicatorParents;
        mSelect = selectDrawableRes;
        mUnSelect = unselectDrawableRes;

        init();
    }

    /**
     * 设置atomicInteger
     */
    private void atomicOption() {
        atomicInteger.incrementAndGet();
        if (atomicInteger.get() > mViews.size() - 1) {
            atomicInteger.getAndAdd(-mViews.size());
        }
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
        }
    }

    public ViewPager getViewPager() {
        return mViewPager;
    }

    public List<View> getViews() {
        return mViews;
    }

    public void setOnViewInstantiateListener(OnViewInstantiateListener listener) {
        mOnViewInstantiateListener = listener;
    }

    /**
     *
     */
    private void init() {
        mPagerAdapter = new PagerAdapter() {
            @Override
            public int getCount() {
                return mViews.size();
            }

            @Override
            public boolean isViewFromObject(View arg0, Object arg1) {
                return arg0 == (arg1);
            }

            @Override
            public int getItemPosition(Object object) {
                View view = (View) object;
                if (mViews.contains(view)) {
                    return mViews.indexOf(view);
                }

                return POSITION_NONE;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView(mViews.get(position));// 删除页卡
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                View view = mViews.get(position);
                container.addView(view, 0);

                if (mOnViewInstantiateListener != null) {
                    mOnViewInstantiateListener.onInstantiate(position, view);
                }

                return mViews.get(position);
            }
        };

        mViewPager.setAdapter(mPagerAdapter);

        mViewPager.addOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                // 从1到2滑动,在1滑动前调用
            }

            @Override
            public void onPageSelected(int position) {
                // activity从1到2滑动,2被加载后掉用此方法
                switchBannerIndicator(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                // 状态有三个0空闲,1是正在滑行中,2目标加载完毕
            }
        });

        if (mIndicatorParents != null) {
            for (int i = 0; i < mViews.size(); i++) {
                // 导航点直接的间距
                int margin = 20;

                // 设置未选中的也没的导航点的图片
                ImageView view = new ImageView(mViewPager.getContext());
                view.setBackgroundResource(mUnSelect);

                // 设置图片的属性
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

                if (i < mViews.size() - 1) {
                    params.rightMargin = margin;
                }

                // 将导航点加入到容器中
                mIndicatorParents.addView(view, params);
            }
            // 单独设置选中的导航点的图片
            mIndicatorParents.getChildAt(0).setBackgroundResource(mSelect);
        }

        /**
         * 判断是否自动更新View
         */
        if (mIsAuto) {
            // 启动线程,定时更改View
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        if (isContinue) {
                            viewHandler.sendEmptyMessage(atomicInteger.get());
                            atomicOption();
                        }
                    }
                }
            }).start();
        }

    }

    /**
     * 设置指示器当前页码
     */
    private void switchBannerIndicator(int index) {
        if (mIndicatorParents != null) {
            for (int i = 0; i < mIndicatorParents.getChildCount(); i++) {
                View view = mIndicatorParents.getChildAt(i);
                if (i == index) {
                    view.setBackgroundResource(mSelect);
                } else {
                    view.setBackgroundResource(mUnSelect);
                }
            }
        }
    }
}
  代码中注释已经很详细了,不多解释,下面来看看如何使用该ViewPagerHelper,我们用它来试下你APP的新手导航页:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

    <LinearLayout
        android:id="@+id/dots_parent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:gravity="center"
        android:layout_marginBottom="20dp"
        android:orientation="horizontal" />

</RelativeLayout>


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;

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

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 新手导航页
 *
 * @author lining
 */
public class GudieActivity extends Activity {

    private List<View> views = null;

    @Bind(R.id.viewpager)
    public ViewPager mViewPager;
    @Bind(R.id.dots_parent)
    public LinearLayout viewPoints;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_guide);

        ButterKnife.bind(this);

        this.initDatas();
    }

    /**
     * 初始化数据
     */
    private void initDatas() {
        views = new ArrayList<View>();

        View view1 = LayoutInflater.from(this).inflate(R.layout.page_guide_first, null);
        View view2 = LayoutInflater.from(this).inflate(R.layout.page_guide_second, null);
        View view3 = LayoutInflater.from(this).inflate(R.layout.page_guide_third, null);

        views.add(view1);
        views.add(view2);
        views.add(view3);

        view3.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(GudieActivity.this, MainActivity.class);
                GudieActivity.this.startActivity(intent);

                GudieActivity.this.finish();
            }
        });

        new ViewPagerHelper(true, mViewPager, views, viewPoints, R.mipmap.page_indicator_focused,
                R.mipmap.page_indicator_unfocused);
    }
}

 注: 请着重看下这行代码:

new ViewPagerHelper(false, mViewPager, views, viewPoints, R.mipmap.page_indicator_focused, R.mipmap.page_indicator_unfocused);
  没错,使用ViewPagerHelper就这么简单的一句!!! 只要把需要的参数传递过去即可啦,看下效果:

ViewPager封装工具类: 轻松实现APP导航或APP中的广告栏_第1张图片


  有没有被惊艳到?

  好吧,确实没啥惊艳的,哈哈,不过我想,该工具类确实能很好的帮助大家精简以后的开发工作!


实例源码下载地址(免费):http://download.csdn.net/detail/zuiwuyuan/9212197


你可能感兴趣的:(viewpager)