无限轮播ViewPager的实现

时间:2022-07-11 10:11:26

MainActivity

package com.jiangtea.vpdemo;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity {

private ViewPager vp;
private TextView tv_title;
private LinearLayout ll_dots;
private int[] resIds;
private String[] titles;
private List<ImageView> imageViews;
private static final int MAX_COUNT = 10000000;
private int currentPostion = MAX_COUNT / 2;//当前选中脚标
private Handler handler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

vp = (ViewPager) findViewById(R.id.vp);
tv_title = (TextView) findViewById(R.id.tv_title);
ll_dots = (LinearLayout) findViewById(R.id.ll_dots);

initData();
initViewPager();
initViewPagerListener();
initDefaultTitleAndDot();
// 给ViewPager设置TouchEvent监听事件,当手按下去的时候,不自动滚动,当手放开的时候再接着滚动
initTouchEvent();

}

/**
* 初始化图片资源
*/
private void initData() {
//图片资源
resIds = new int[]{R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d, R.drawable.e};
titles = new String[]{"标题1", "标题2", "标题3", "标题4", "标题5"};
imageViews = new ArrayList<ImageView>();
//初始化ImageView 条目
for (int i = 0; i < resIds.length; i++) {
ImageView imageView = new ImageView(this);
imageView.setImageResource(resIds[i]);
//给ImageView设置布局参数
imageView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
//给ImageView设置缩放的方式
imageView.setScaleType(ImageView.ScaleType.CENTER);//等比例缩放,匹配父亲尺寸,可能会有图片损失
imageViews.add(imageView);
}
initDots();
}

/**
* 初始化圆点
*/
private void initDots() {
for (int i = 0; i < resIds.length; i++) {
ImageView imageView = new ImageView(this);
imageView.setBackgroundResource(R.drawable.dot_selector);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
if (i != 0) {
params.leftMargin = 5;//设置而左边距
}
ll_dots.addView(imageView, params);
}
}

/**
* 初始化vp适配器
*/
private void initViewPager() {
vp.setAdapter(new MyAdapter());
//让ViwPager的默认值改为Integer.MAX_VALUE/2
vp.setCurrentItem(currentPostion);

}


private void initDefaultTitleAndDot() {
tv_title.setText(titles[currentPostion % resIds.length]);
ll_dots.getChildAt(currentPostion % resIds.length).setSelected(true);
}

private void initViewPagerListener() {
vp.setOnPageChangeListener(new OnPageChangeListener() {

//当新的页面被选中(成为当前页的时候)回调
@Override
public void onPageSelected(int position) {

ll_dots.getChildAt(currentPostion % resIds.length).setSelected(false);
tv_title.setText(titles[position % resIds.length]);
ll_dots.getChildAt(position % resIds.length).setSelected(true);
currentPostion = position;
}

/**
* 参数1:当前正在滚动的页面的脚标
* 参数2:滚动的百分比0-100%
* 参数3:滚动的像素值
*/
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
Log.d("tag", "onPageScrolled:position=" + position + "/positionOffset=" + positionOffset + "/positionOffsetPixels=" + positionOffsetPixels);
}

@Override
public void onPageScrollStateChanged(int state) {
Log.d("tag", "onPageScrollStateChanged=" + state);
}
});
}


private void startAutoChange() {
handler.postDelayed(new Runnable() {
@Override
public void run() {
// 这里的run方法是在主线程中执行
//Log.d("tag", "ThreadName="+Thread.currentThread().getName());
vp.setCurrentItem(currentPostion + 1, true);
startAutoChange();
}
}, 2000);
}

private void initTouchEvent() {
vp.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
//终止自动轮播
//该方法会移除所有的消息
handler.removeCallbacksAndMessages(null);
break;
case MotionEvent.ACTION_MOVE:

break;
case MotionEvent.ACTION_UP:
//开始自动轮播
startAutoChange();
break;
default:
break;
}
return true;//返回false可以滑动
}
});
}


class MyAdapter extends PagerAdapter {

@Override
public int getCount() {
return MAX_COUNT;//0 MAX_VALUE
}

/**
* 参数1:container,其实就是ViewPager本身
* 参数2:脚标
*/
@Override
public Object instantiateItem(ViewGroup container, int position) {
//把ImageView添加到ViewPager中
container.addView(imageViews.get(position % resIds.length));
Log.d("tag", "instantiateItem=" + position);
//通用的做法,往ViewPager中添加的哪个View,就将哪个View返回
return imageViews.get(position % resIds.length);
}

/**
* 参数1:container,ViewPager本身
* 参数3:是instantiateItem的返回值,用不到
*/
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
//super.destroyItem(container, position, object);
//手动的将对应角标的ImageView,从ViewPager中移除
Log.d("tag", "destroyItem=" + position);
container.removeView(imageViews.get(position % resIds.length));
}

//其实就是判断添加的View跟你返回的Object是不是同一个对象
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}

}

@Override
protected void onStart() {
super.onStart();
startAutoChange();
}

@Override
protected void onDestroy() {
super.onDestroy();

}

@Override
protected void onStop() {
super.onStop();
handler.removeCallbacksAndMessages(null);
}

}
布局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="200dp"
>

<android.support.v4.view.ViewPager
android:id="@+id/vp"
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="#50ff0000"
>
</android.support.v4.view.ViewPager>

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignParentBottom="true"
android:background="#50000000"
>

<TextView
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:text="这是标题"
android:textColor="#fff"
/>

<LinearLayout
android:id="@+id/ll_dots"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="5dp"
android:orientation="horizontal"
/>

</RelativeLayout>
</RelativeLayout>
</RelativeLayout>
drawable下

dot_selector

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_selected="true" android:drawable="@drawable/dot_red"></item>
<item android:drawable="@drawable/dot_normal"></item>
</selector>
dot_red

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

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