偷下懒没上动图,只简单的截个图
先上代码
1、activity_main.xml
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="140dp">
<android.support.v4.view.ViewPager
android:id="@+id/banner_viewpager"
android:layout_width="match_parent"
android:layout_height="140dp" />
<LinearLayout
android:id="@+id/point_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:layout_marginBottom="5dp"
android:orientation="horizontal">
</LinearLayout>
</RelativeLayout>
2、初始化数据,重点是在图片数组头部插入最后一张图片在尾部插入第一张图片
private void initData(){
imgList.add(new Image("第三张图片",R.drawable.image3));//将最后一张图片插入到头部
imgList.add(new Image("第一张图片",R.drawable.image1));//第一张图片
imgList.add(new Image("第二张图片",R.drawable.image2));//第二张
imgList.add(new Image("第三张图片",R.drawable.image2));//第三张
imgList.add(new Image("第一张图片"),R.drawable.image1);//将第一张图片追加到尾部
}
3、适配器
PagerAdapter pagerAdapter = new PagerAdapter() {
@Override
public int getCount() {
return imgList.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view==object;
}
@Override
public Object instantiateItem(ViewGroup container, final int position) {
Image image = imgList.get(position);
int imageId = image.getImageId();
ImageView imageView = new ImageView(activity);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams
(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
imageView.setImageResource(imageId);
imageView.setLayoutParams(params);
container.addView(imageView);
return imageView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
};
3、设置ViewPaper
viewpager.setAdapter(pagerAdapter);
viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
//改变指示点的状态
//把当前点enbale 为true
position = position%pointGroup.size();
pointGroup.getChildAt(position).setEnabled(true);
//把上一个点设为false
pointGroup.getChildAt(lastPosition).setEnabled(false);
lastPosition = position;
if (position == imageList.size() - 1) {// 设置当前值为1
currentPosition = 1;
} else if (position == 0) {// 如果索引值为0了,就设置索引值为倒数第二个
currentPosition = imageList.size() - 2;
} else {
currentPosition = position;
}
}
@Override
public void onPageScrollStateChanged(int state) {//如果是静止状态,将当前页进行替换
if(state==ViewPager.SCROLL_STATE_IDLE){// 设置当前页,smoothScroll 平稳滑动
banner_viewpager.setCurrentItem(currentPosition, false);
}
}
});