Android:ViewPager循环、自动滚动效果

释放双眼,带上耳机,听听看~!

原理图

ViewPager循环、自动滚动,这种效果很常见,一般app首页都会有焦点图、或者用户引导页面。第三方比较好用的我推荐阿里开源的UltraViewPager,毕竟大公司的,用着放心吧 ๑乛◡乛๑。轮子虽好,不过自己也还是需要会写吧。

有2种方案实现循环滚动,一种是在PagerAdapter设置最大数量为int最大值,另一种就是本文实现的。前一种感觉有点奇怪,如果不带自动循环滚动的话还可以用,毕竟用户一般不会切换这么多次能看到头。而对于循环滚动的话,需要本文的类似思路实现起来比较好一点吧,原理看上图即可。例子效果图在最后。

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.AttrRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

/**
 * 封装的viewpager
 * Created by WZH on 2017/12/14.
 */

public class AutoScrollViewPager<T extends PagerAdapter> extends FrameLayout {
    private ViewPager viewPager ;
    private PagerAdapter mAdapter ;
    private LinearLayout mLinearLayout ;
    private Context mContext ;
    private int pageMargin = 0 ;
    private int oldPosition = 0 ; //上一个位置
    private int currentIndex = 1 ; //当前位置
    private static long time = 3000 ; //自动播放时间
    private static boolean autoPlay = true ; //是否自动播放

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            play();
        }
    };
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            viewPager.setCurrentItem(++currentIndex);
        }
    };

    public AutoScrollViewPager(@NonNull Context context) {
        this(context,null);
    }

    public AutoScrollViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public AutoScrollViewPager(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    /**
     * 动态添加viewpager和小圆点
     */
    private void init() {
        mContext = getContext() ;
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        setClipChildren(false);
        pageMargin = getResources().getDimensionPixelSize(R.dimen.page_margin);

        viewPager = new ViewPager(mContext);
        LayoutParams vparams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        vparams.leftMargin = pageMargin * 2;
        vparams.rightMargin = pageMargin * 2 ;
        viewPager.setLayoutParams(vparams);
        addView(viewPager);

        mLinearLayout = new LinearLayout(mContext);
        LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.BOTTOM ;
        mLinearLayout.setGravity(Gravity.CENTER);
        mLinearLayout.setOrientation(LinearLayout.HORIZONTAL);
        addView(mLinearLayout,params);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        play();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        cancel();
    }

    /**
     * 初始化viewpager
     */
    private void initViewPager() {
        if (mAdapter==null){
            return;
        }
        viewPager.setCurrentItem(currentIndex);
        //设置红缓存的页面数
        viewPager.setOffscreenPageLimit(1);
        // 设置2张图之前的间距。
        viewPager.setPageMargin(pageMargin);
//        viewPager.setPageTransformer(true, new ZoomOutPageTransformer());
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset,int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                if (position==0){
                    currentIndex = mAdapter.getCount()-2 ;
                }else if (position == mAdapter.getCount()-1){
                    currentIndex = 1 ;
                }else {
                    currentIndex = position ;
                }
                //此处currentIndex是从1开始的,要注意
                mLinearLayout.getChildAt(oldPosition).setEnabled(false);
                mLinearLayout.getChildAt(currentIndex-1).setEnabled(true);
                oldPosition = currentIndex-1 ;
                Log.e("wenzhihao","position=="+position+",currentIndex="+currentIndex);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if(state==ViewPager.SCROLL_STATE_IDLE){
                    viewPager.setCurrentItem(currentIndex,false);
                    play();
                }else if(state==ViewPager.SCROLL_STATE_DRAGGING){
                    cancel();
                }
            }
        });
        setIndicatorDot();
        mLinearLayout.getChildAt(0).setEnabled(true);
    }

    /**
     * 播放,根据autoplay
     */
    public void play(){
        if (autoPlay){
            handler.postDelayed(runnable,time);
        }else {
            handler.removeCallbacks(runnable);
        }
    }
    /**
     * 取消播放
     */
    public void cancel(){
        handler.removeCallbacks(runnable);
    }

    /**
     * 设置小圆点
     */
    private void setIndicatorDot() {
        for (int i = 0;i<mAdapter.getCount()-2;i++){
            //添加底部灰点
            View v = new View(mContext);
            v.setBackgroundResource(R.drawable.bg_dot);
            v.setEnabled(false);
            //指定其大小
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(20,20);
            if (i != 0)
                params.leftMargin = 20;
            params.bottomMargin = 20;
            v.setLayoutParams(params);
            mLinearLayout.addView(v);
        }
    }

    /**
     * 设置适配器
     * @param adpter
     */
    public void setAdapter(T adpter){
        mAdapter = adpter ;
        viewPager.setAdapter(mAdapter);
        initViewPager();
    }

    /**
     * 设置是否自动播放
     * @param autoPlay
     */
    public void setAutoPlay(boolean autoPlay) {
        AutoScrollViewPager.autoPlay = autoPlay;
        if (!autoPlay){
            handler.removeCallbacks(runnable);
        }
    }
}

注意主要几点

  • 组合控件,一个FrameLayout布局包含ViewPager和一个小圆点指示器。
  • 自动循环用handler实现,循环发送消息。
  • 这里需要注意的是setAdapter( )方法,只要正常写PageAdapter传入即可;
  • 在OnPageChangeListener中,onPageSelected的时候去处理位置问题,就是图中所说的,从左往右滑动,position==0的时候切换到4的位置,当从右往左滑动的时候,positon==5的时候切换到1的位置。onPageScrollStateChanged状态改变的时候,即停止滑动的时候滑到指定位置,当手指拖动的时候需要停止自动播放;
  • 小圆点指示器,是一个线性布局根据图片数量添加原点,原点背景为selector;
  • 在屏幕显示的时候设置自动播放,离开屏幕时候停止播放;
  • 如果想显示3个page需要在viewpager父容器设置
android:clipChildren="false"
android:layerType="hardware"
//代码如下
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
setClipChildren(false);

并且设置viewPager.setPageMargin(pageMargin);,需要加其他特效可以自定义PageTransformer。

  • setAutoPlay方法可以设置不自动循环 viewPager.setAutoPlay(false);

例子

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:layout_height="match_parent">
   <com.wzh.AutoScrollViewPager
       android:id="@+id/viewpager"
       android:layout_width="match_parent"
       android:layout_height="300dp">
   </com.wzh.AutoScrollViewPager>
</LinearLayout>

MainActivity.java

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private AutoScrollViewPager viewPager ;
    private ViewPagerAdapter adapter ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        viewPager = (AutoScrollViewPager) findViewById(R.id.viewpager);
        adapter = new ViewPagerAdapter(this);
        viewPager.setAdapter(adapter);
        viewPager.setAutoPlay(true);
    }

}

ViewPagerAdapter.java

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;

/**
 * Created by WZH on 2018/4/14.
 */

public class ViewPagerAdapter extends PagerAdapter {
    private String[] resIds = {
            //最后一张图片
            "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1523772064849&di=7502440dd81352d3e3d584eb810e0acc&imgtype=0&src=http%3A%2F%2Fimage.tianjimedia.com%2FuploadImages%2F2012%2F265%2F5432CKKPF561_1000x500.jpg",
            //正真的5张图片
            "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1523772064850&di=dd3588fdf916fce1527f7b53cc536293&imgtype=0&src=http%3A%2F%2Fimage.tianjimedia.com%2FuploadImages%2F2012%2F088%2F9KF35LBMFO74.jpg",
            "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1523772064854&di=165a16c1167b38b067b3c82cb830c347&imgtype=0&src=http%3A%2F%2Fattachments.gfan.com%2Fforum%2Fattachments2%2F201303%2F18%2F110902j0e5zjwj0yutt00j.jpg",
            "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1523772064877&di=dac68b830070fb6dbf1a9d71fc6b2772&imgtype=0&src=http%3A%2F%2Fi3.download.fd.pchome.net%2Fg1%2FM00%2F0D%2F18%2FoYYBAFS8sGGIUf9wAAJfpTlwpsgAACPGwFaL6cAAl-9928.jpg",
            "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1523772294591&di=9633b23326710637bda3b511c87e0fdb&imgtype=jpg&src=http%3A%2F%2Fimg0.imgtn.bdimg.com%2Fit%2Fu%3D1163084700%2C3470735618%26fm%3D214%26gp%3D0.jpg",
            "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1523772064849&di=7502440dd81352d3e3d584eb810e0acc&imgtype=0&src=http%3A%2F%2Fimage.tianjimedia.com%2FuploadImages%2F2012%2F265%2F5432CKKPF561_1000x500.jpg",
            //第一张图片
            "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1523772064850&di=dd3588fdf916fce1527f7b53cc536293&imgtype=0&src=http%3A%2F%2Fimage.tianjimedia.com%2FuploadImages%2F2012%2F088%2F9KF35LBMFO74.jpg",
    };

    private Context context ;
    public ViewPagerAdapter(Context context) {
        this.context = context ;
    }

    @Override
    public int getCount() {
        return resIds.length;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View view = View.inflate(context, R.layout.vp_item, null);
        ImageView imageView = (ImageView) view.findViewById(R.id.image);
        Glide.with(context)
                .load(resIds[position])
                .into(imageView);
//        imageView.setImageResource(resIds[position]);
        //添加到容器中
        container.addView(view);
        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

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

// bg_while.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <size android:width="30dp" android:height="30dp"/>
    <!--白色-->
    <solid android:color="#ffffff" />
    <!--半径-->
    <corners android:radius="10dp" />
</shape>

//bg_gray.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <size android:width="20dp" android:height="20dp"/>
    <!--灰色-->
    <solid android:color="#88aaaaaa" />
    <!--半径-->
    <corners android:radius="10dp" />

</shape>

//bg_dot.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/bg_while" android:state_enabled="true" />
    <item android:drawable="@drawable/bg_gray" android:state_enabled="false" />
</selector>

效果图

image

人已赞赏
Android文章

Android本地分享

2019-10-13 15:18:19

Android文章

Android沉浸式状态栏三方库Immersionbar覆盖基类

2019-10-13 21:57:54

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索