Android ViewPager 小圆点指示器

时间:2022-02-13 16:34:33
一个很常用的功能,一个ViewPager会自动滚动,并且有一排小圆点黑和白来指示当前的滚动进度

首先写一个ViewPager的适配器,这里这个适配器为了方便里面的元素全都是ImageView

import android.content.Context;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Interpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Scroller;



/**
* Created by Administrator on 2016/2/24.
*/
public class HomeHomeBannerAdapter extends PagerAdapter{
private Context context;
private ImageView[] eventImageViews;
private String[] eventUrls;
int destWidth,destHeight;


public HomeHomeBannerAdapter(Context context, String[] eventUrls,int destWidth,int destHeight) {
this.context = context;
this.eventUrls = eventUrls;
this.destHeight = destHeight;
this.destWidth = destWidth;
initImageViews();
}

/**
* 初始化viewPager里的几张图
*/
private void initImageViews(){
if(eventUrls==null)return;
eventImageViews = new ImageView[eventUrls.length];
for (int i=0;i<eventUrls.length;i++) {
eventImageViews[i] = new ImageView(context);
eventImageViews[i].setLayoutParams(new LinearLayout.LayoutParams(destWidth, destHeight));
eventImageViews[i].setPadding(0, 0, 0, 0);
eventImageViews[i].setScaleType(ImageView.ScaleType.FIT_XY);
JImageUtils.loadImageFromServerByUrl(context,eventImageViews[i],eventUrls[i]);
}//显示图片
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
if (eventImageViews != null && eventImageViews.length > position && position >= 0)
container.removeView(eventImageViews[position]);

}

@Override
public Object instantiateItem(ViewGroup container, int position) {
container.addView(eventImageViews[position], 0);
return eventImageViews[position];
}

@Override
public int getCount() {return eventUrls==null?0:eventUrls.length;}

@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
//ViewPager监听器集成到内部类去
static public class EventViewPagerChangeListener implements ViewPager.OnPageChangeListener {
LinearLayout llGuideGroup;
int oldEventPosition;
int currentItem;

public EventViewPagerChangeListener(LinearLayout llGuideGroup){
this.llGuideGroup = llGuideGroup;
}

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

/**
* 控制小点的白色还是黑色的显示
* @param position
*/
public void onPageSelected(int position) {
llGuideGroup.getChildAt(oldEventPosition).setBackgroundResource(R.drawable.dot_normal);//黑色点
llGuideGroup.getChildAt(position).setBackgroundResource(R.drawable.dot_focused);//白色点
oldEventPosition = position;
currentItem = position;
}

@Override
public void onPageScrollStateChanged(int state) {

}
}

/**
* 控制viewpager自动滑动的定时任务
*/
public static class ScrollTask implements Runnable {
EventViewPagerChangeListener listener;
ViewPager vpEvent;
int eventSize;
Handler handler;
public ScrollTask(EventViewPagerChangeListener listener,final ViewPager vpEvent, int eventSize){
this.listener = listener;
this.vpEvent = vpEvent;
this.eventSize = eventSize;
handler = new Handler();
}
public void run() {
if(listener==null||vpEvent==null||eventSize==0)return;
listener.currentItem = (listener.currentItem + 1) % eventSize;
Log.i("Alex","currentItem是"+listener.currentItem);
handler.post(new Runnable() {
@Override
public void run() {
vpEvent.setCurrentItem(listener.currentItem); // 通过Handler切换图片
}
});
}
}

public static class FixedSpeedScroller extends Scroller {
private static final int mDuration = 400;
private int eventCount;

public FixedSpeedScroller(Context context, Interpolator interpolator,int eventCount) {
super(context, interpolator);
this.eventCount = eventCount;
}

@Override
public void startScroll(int startX, int startY, int dx, int dy, int duration) {
if (duration % 100 == 0 && duration > 0) {
//"现在是自动划"
if (duration / 100 == eventCount) super.startScroll(startX, startY, dx, dy, 1);//如果是最后一张
else super.startScroll(startX, startY, dx, dy, mDuration);

} else {
// "现在是手动划"
super.startScroll(startX, startY, dx, dy, 80);
}
}
}
}

在上面适配器的内部类有一个监听器,这个监听器里有一个成员LinearLayout llGuideGroup,这个线性布局里面装有几个小点,下面是这个布局的定义

<RelativeLayout
android:id="@+id/rlEvents"
android:layout_width="match_parent"
android:layout_height="200dp"
android:visibility="gone">

<android.support.v4.view.ViewPager
android:id="@+id/vpEvent"
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="@color/black666666" />

<LinearLayout
android:id="@+id/llGuideGroup"
android:layout_width="match_parent"
android:layout_height="10dp"
android:layout_alignParentBottom="true"
android:layout_marginBottom="10dp"
android:layout_centerHorizontal="true"
android:gravity="center"
android:orientation="horizontal" >

</LinearLayout>
</RelativeLayout>

设置小圆点的数量并初始化监听器

/**
* 向一个线性布局里添加小圆点,具体的控制逻辑在listener里
* @param llGuideGroup
* @param count 要添加多少个小圆点
*/
public EventViewPagerChangeListener addViewPagerDots(LinearLayout llGuideGroup,ViewPager vpEvents,int count){
if(llGuideGroup==null||vpEvents==null||count<1)return null;
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(15, 15);
lp.leftMargin = 5;
lp.rightMargin = 5;
for(int i=0;i<count;i++){
ImageView imageView = new ImageView(llGuideGroup.getContext());
imageView.setLayoutParams(lp);
imageView.setBackgroundResource(i==0?R.drawable.dot_focused:R.drawable.dot_normal);
llGuideGroup.addView(imageView);
}
//控制小圆点显示的监听器
EventViewPagerChangeListener listener = new EventViewPagerChangeListener(llGuideGroup);
vpEvents.addOnPageChangeListener(listener);
return listener;
}

通过多线程实现定时切换页面

HomeHomeBannerAdapter.EventViewPagerChangeListener listener = producer.addViewPagerDots(holder.llGuideGroup,holder.viewPager,eventUrls.length);//添加用于指示的小圆点
// 当Activity显示出来后,每3秒钟切换一次图片显示
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
scheduledExecutorService.scheduleAtFixedRate(new HomeHomeBannerAdapter.ScrollTask(listener,holder.viewPager,eventUrls.length), 3, 3, TimeUnit.SECONDS);

设置自定义滚动器降低viewPager的切换速度

/**
* 给ViewPager设置自定义的滚动器,降低默认的滚动速度
* @param vpEvent
*/
public void setViewPagerScroller(ViewPager vpEvent){
if(vpEvent==null)return;
Field mField;
Scroller mScroller;
try {
mField = ViewPager.class.getDeclaredField("mScroller");
mField.setAccessible(true);
mScroller = new HomeHomeBannerAdapter.FixedSpeedScroller(vpEvent.getContext(), new AccelerateInterpolator(),vpEvent.getChildCount());
try {
mField.set(vpEvent, mScroller);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}