【Android-轮播图实现】轮播图实现原理及源码

实现原理:

  1. 设置viewpage控件
  2. 初始化控件,设置adapter继承自pagerAdapter
  3. 将图片设置到adapter中,并实现adapter中的其他方法
  4. 实现左右无限轮播
  5. 利用handler实现自动轮播
  6. 利用linstener实现指示器(小圆点)功能

MainActivity.java:

public class MainActivity extends AppCompatActivity implements MyViewPager.OnViewPagerTouchLinstener, ViewPager.OnPageChangeListener {

    private MyViewPager mLooperpage;
    private LooperPageAdapter mLooperPageAdapter;
    private static List<Integer> sPics=new ArrayList<>();
    private boolean mIsTouch=false;

    //在静态代码块中初始化
    static {
        sPics.add(R.mipmap.picture0);
        sPics.add(R.mipmap.picture1);
        sPics.add(R.mipmap.picture2);
    }

    private Handler mHandler;
    private LinearLayout mPointContainer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
	mHandler = new Handler();
    }

    @Override
    public void onAttachedToWindow() {
        //当这个界面绑定到窗口的时候(即当这个窗口开着的时候才进行无限循环)
        //当绑定上窗口的时候handler就去执行runnable
        mHandler.post(mLoopTask);
    }

    @Override
    public void onDetachedFromWindow() {
        //没有绑定窗口的时候handler就解除绑定,释放runnable资源
        mHandler.removeCallbacks(mLoopTask);
    }

    private Runnable mLoopTask =new Runnable() {
        @Override
        public void run() {
            if (! mIsTouch){      //默认是false
                //在runnable中完成自动切换轮播图的功能
                int currentItem=mLooperpage.getCurrentItem();
                mLooperpage.setCurrentItem(++ currentItem,false);
            }
             mHandler.postDelayed(this,2000);
        }
    };


    private void initView() {
        mLooperpage =(MyViewPager)this. findViewById(R.id.looper_pager);
        //设置适配器
        mLooperPageAdapter = new LooperPageAdapter();
        mLooperPageAdapter.setData(sPics);
        mLooperpage.setAdapter(mLooperPageAdapter);
        mLooperpage.addOnPageChangeListener(this);
        //通过实现该方法来达到监听是否触摸的效果,具体逻辑在MyViewPager中
        mLooperpage.setOnViewPagerTouchLinstener(this);

        mPointContainer = findViewById(R.id.point_container);
        //根据图片的个数去添加点的个数
        insertPoint();
        mLooperpage.setCurrentItem(mLooperPageAdapter.getDataRealSize() /2 +1,false);
    }

    private void insertPoint() {
        for (int i = 0; i < sPics.size(); i++) {
            View point =new View(this);
            point.setBackground(getResources().getDrawable(R.drawable.shape_point_normal));

            LinearLayout.LayoutParams layoutParams=new LinearLayout.LayoutParams(40,40);
            layoutParams.leftMargin=20;

            point.setLayoutParams(layoutParams);    //将point的属性设置进point中
            mPointContainer.addView(point);         //将point设置到LinearLayout中去
        }
    }

    @Override
    public void onPagerTouch(boolean isTouch) {
        mIsTouch =isTouch;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        int realPosition;
        //这个方法的调用其实是viewPager停下来之后选中的位置
        if(mLooperPageAdapter.getDataRealSize() != 0){
            realPosition= position % mLooperPageAdapter.getDataRealSize();
        }else {
            realPosition=0;
        }
        setSelectPoint(realPosition);   //设置圆点点
    }

    private void setSelectPoint(int realPosition) {
        for (int i = 0; i < mPointContainer.getChildCount(); i++) {
            View point=mPointContainer.getChildAt(i);   //对LinearLayout中的点点进行一个遍历
            if (i != realPosition){ //如果i不是正在改变的图片,就是默认颜色
                point.setBackground(getResources().getDrawable(R.drawable.shape_point_normal));
            }else{      //如果i是正在改变的图片,就设置为选中的圆点点
                point.setBackground(getResources().getDrawable(R.drawable.shape_point_selected));
            }
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}

LooperPageAdapter.java:

public class LooperPageAdapter extends PagerAdapter {
    private List<Integer> mPics=null;

    @Override
    public int getCount() {
        if (mPics != null){
            return Integer.MAX_VALUE;
        }
        return 0;
    }

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

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        //初始化
        ImageView imageView=new ImageView(container.getContext());
        //设置背景色
        //imageView.setBackgroundColor(mColor.get(position));
        //将背景色添加到container中
        int realPosition=position % mPics.size();

        imageView.setImageResource(mPics.get(realPosition));

        container.addView(imageView);
        return imageView;
    }


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

    public void setData(List<Integer> sColor) {
        this.mPics=sColor;
    }

    //面向对象的思想,获取到数组的长度
    public int getDataRealSize(){
        if (mPics != null) {
            return mPics.size();
        }
        return 0;
    }
}

MyViewPager.java:

public class MyViewPager extends ViewPager {

    private OnViewPagerTouchLinstener mTouchLinstener;

    public MyViewPager(@NonNull Context context) {
        super(context);
    }

    public MyViewPager(Context context, AttributeSet attrs) {
        super(context,attrs);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        //只要这部分被触摸了,就设置接口回调出去

        switch (ev.getAction()){
            case MotionEvent.ACTION_DOWN:   //触摸上时
                if (mTouchLinstener != null) {
                    mTouchLinstener.onPagerTouch(true);
                }
                break;
            case MotionEvent.ACTION_CANCEL:
                break;
            case MotionEvent.ACTION_UP:     //松开时,
                if (mTouchLinstener != null) {
                    mTouchLinstener.onPagerTouch(false);
                }
                break;
        }
        return super.onTouchEvent(ev);
    }

    public void setOnViewPagerTouchLinstener(OnViewPagerTouchLinstener listener){
        this.mTouchLinstener=listener;
    }

    public interface OnViewPagerTouchLinstener{
        void onPagerTouch(boolean isTouch);
    }
}

activity_main.layout:

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

    <com.example.looperpager.MyViewPager
        android:id="@+id/looper_pager"
        android:layout_width="match_parent"
        android:layout_height="200dp" />

    <LinearLayout
        android:id="@+id/point_container"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="40px"
        android:gravity="center"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </LinearLayout>

</RelativeLayout>

shape_point_normal:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <size android:height="40px" android:width="40px"/>
    <solid android:color="#021741"/>
</shape>

shape_point_selected:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <size android:width="10px" android:height="10px"/>
    <solid android:color="#126784"/>
</shape>

你可能感兴趣的:(Android学习,#,activity)