ViewPager的广告条轮播
首先布局
<?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="match_parent"
>
<android.support.v4.view.ViewPager
android:id="@+id/viewpagerAD"
android:layout_width="match_parent"
android:layout_height="160dp"
/>
<LinearLayout
android:id="@+id/dot_layout"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_marginTop="130dp"
android:orientation="horizontal"
android:gravity="center_vertical"
android:background="#66000000" >
<View
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<ImageView
android:id="@+id/dot1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@null"
android:src="@mipmap/dot_enable" />
<ImageView
android:id="@+id/dot2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@null"
android:src="@mipmap/dot_normal"
android:layout_marginLeft="20dp" />
<ImageView
android:id="@+id/dot3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@null"
android:src="@mipmap/dot_normal"
android:layout_marginLeft="20dp" />
<View
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
</RelativeLayout>
代码一:使用Handler递归实现
public class MainActivity extends AppCompatActivity {
private ViewPager mViewPager;
private List<ImageView> mADViews;
private static final int[] AD_RES = {R.mipmap.a, R.mipmap.b, R.mipmap.c};
private ADAdapter mADAdapter;
private List<ImageView> mDotViews;
//2-2 通过Handler+postdelayed递归
private Handler mAdHandler = new Handler() {
@Override
public void close() {
}
@Override
public void flush() {
}
@Override
public void publish(LogRecord record) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mADViews = new ArrayList<ImageView>();
for (int i = 0; i < AD_RES.length; i++) {
//通过代码创建ImageView
ImageView imageView = new ImageView(this);
imageView.setLayoutParams(new LinearLayout.LayoutParams(ViewPager.LayoutParams.MATCH_PARENT, ViewPager.LayoutParams.MATCH_PARENT));
//设置图片拉伸方式
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
//给图片指定资源
imageView.setImageResource(AD_RES[i]);
mADViews.add(imageView);
}
mViewPager = (ViewPager) findViewById(R.id.viewpagerAD);
//绑定适配器
mADAdapter = new ADAdapter(mADViews);
mViewPager.setAdapter(mADAdapter);
// 通过Handler+postdelayed递归
mViewPager.postDelayed(new ADRunnable(), 2000);
//先把所有圆点放入数组
mDotViews = new ArrayList<ImageView>();
mDotViews.add((ImageView) findViewById(R.id.dot1));
mDotViews.add((ImageView) findViewById(R.id.dot2));
mDotViews.add((ImageView) findViewById(R.id.dot3));
//ViewPager的滑动监听
mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
// 滑动状态改变的时候触发,参数表示当前显示的位置
for (int i = 0; i < mDotViews.size(); i++) {
if (i != position) {
mDotViews.get(i).setImageResource(R.mipmap.dot_normal);
} else {
mDotViews.get(i).setImageResource(R.mipmap.dot_enable);
}
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
//2-1 定义循环执行的任务:就是让当前下标++,调用setCurrentItem()
class ADRunnable implements Runnable {
@Override
public void run() {
//获得当前显示item的下标
int nowIndex = mViewPager.getCurrentItem();
//下标自增
nowIndex++;
if (nowIndex > mADViews.size() - 1) {
nowIndex = 0;
}
//重新设置显示的位置
mViewPager.setCurrentItem(nowIndex);
//递归
mViewPager.postDelayed(new ADRunnable(), 2000);
}
}
}
/**
* 1-3 自定义的PagerAdapter
* @author Bodhixu
*
*/
public class ADAdapter extends PagerAdapter{
//数据源
private List<ImageView> mViews;
public ADAdapter(List<ImageView> views) {
this.mViews = views;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mViews.size();
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
// TODO Auto-generated method stub
return arg0 == arg1;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
// TODO Auto-generated method stub
View view = mViews.get(position);
container.addView(view);
return view;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
// TODO Auto-generated method stub
container.removeView(mViews.get(position));
}
}
代码二:使用Timer来实现(防止越来越快)
import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.gtercn.oneday.R; import com.gtercn.oneday.base.BaseFragment; import com.gtercn.oneday.bean.ImageBean; import java.util.ArrayList; import java.util.List; public class HomeFragment extends BaseFragment implements ViewPager.OnPageChangeListener{ private static final String TAG = HomeFragment.class.getSimpleName(); private ViewPager mViewPager; private ViewPagerAdapter mViewPagerAdapter; private LinearLayout mWrapDots; private List<ImageBean> mImageList; private ImageView[] mDots; private ImageView mImageView; private int currentIndex; private Thread mThread; private boolean mFlag = true; private static final int TIME = 3000; private Handler mHandler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { if (msg.what == 0) { int nowIndex = mViewPager.getCurrentItem(); mViewPager.setCurrentItem(++nowIndex); } return false; } }); @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public void onAttach(Context context) { super.onAttach(context); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.fragment_home,container,false); mViewPager = (ViewPager) view.findViewById(R.id.home_vp) ButterKnife.bind(this, view); addPictures(); mDots = new ImageView[mImageList.size()]; initDots(view); mViewPagerAdapter = new ViewPagerAdapter(mImageList, getContext()); mViewPager.setAdapter(mViewPagerAdapter); mViewPager.setOffscreenPageLimit(500); mViewPager.setOnPageChangeListener(this); return view; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } @Override public void onDestroy() { super.onDestroy(); } @Override public void onDestroyView() { super.onDestroyView(); } @Override public void onDetach() { super.onDetach(); } @Override public void onPause() { super.onPause(); mFlag = false; mThread.interrupt(); } @Override public void onResume() { super.onResume(); mFlag = true; showPicture(); } @Override public void onStart() { super.onStart(); } @Override public void onStop() { super.onStop(); } /** * 初始化小圆点方法; * * @param view */ private void initDots(View view) { mWrapDots = (LinearLayout) view.findViewById(R.id.wrap_dots_ll); for (int i = 0; i < mImageList.size(); i++) { mImageView = new ImageView(getContext()); mDots[i] = (ImageView) mWrapDots.getChildAt(i); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(12, 12); lp.setMargins(3, 0, 3, 0); mDots[i] = mImageView; mWrapDots.addView(mDots[i], lp); } currentIndex = 0; mDots[currentIndex].setImageResource(R.drawable.circular_point_shape_selected); } public void setCurrentSelected(int index) { for (int i = 0; i < mImageList.size(); i++) { if (i == index) { mDots[i].setImageResource(R.drawable.circular_point_shape_selected); } else { mDots[i].setImageResource(R.drawable.circular_point_shape); } } } private void addPictures() { mImageList = new ArrayList<>(); mImageList.add(new ImageBean(R.mipmap.home_ad_btm1)); mImageList.add(new ImageBean(R.mipmap.home_imageview_btm1)); mImageList.add(new ImageBean(R.mipmap.home_imageview_btm2)); mImageList.add(new ImageBean(R.mipmap.home_ad_btm1)); mImageList.add(new ImageBean(R.mipmap.home_imageview_btm1)); } void showPicture() { mThread = new Thread(new Runnable() { @Override public void run() { while (mFlag) { try { mHandler.sendEmptyMessage(0); Thread.sleep(TIME); } catch (InterruptedException e) { e.printStackTrace(); } } } }); mThread.start(); } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { setCurrentSelected(position % mImageList.size()); } @Override public void onPageScrollStateChanged(int state) { } class ViewPagerAdapter extends PagerAdapter { private List<ImageBean> imageList; private Context context; public ViewPagerAdapter(List<ImageBean> imageList, Context context) { this.imageList = imageList; this.context = context; } @Override public int getCount() { return imageList != null ? Integer.MAX_VALUE : 0; } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public Object instantiateItem(ViewGroup container, final int position) { View view = LayoutInflater.from(context).inflate(R.layout.item_viewpager, container, false); ImageView imageView = (ImageView) view.findViewById(R.id.image_item_vp); imageView.setBackgroundResource(imageList.get(position % imageList.size()).getImageId()); container.addView(view); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getContext(), "你点击了第" + (position % imageList.size() + 1) + "个图片", Toast.LENGTH_SHORT).show(); } }); return view; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } } }
fragment_home的布局文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <ScrollView android:layout_width="match_parent" android:layout_height="wrap_content" android:scrollbars="none"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <FrameLayout android:layout_width="match_parent" android:layout_height="200dp" android:layout_alignParentBottom="true" android:alpha="0.6"> <android.support.v4.view.ViewPager android:id="@+id/home_vp" android:layout_width="match_parent" android:layout_height="match_parent" /> <LinearLayout android:id="@+id/wrap_dots_ll" android:layout_width="wrap_content" android:layout_height="30dp" android:layout_gravity="bottom|center_horizontal" android:gravity="center" android:orientation="horizontal" /> </FrameLayout> </LinearLayout> </ScrollView> </LinearLayout>
item_viewpager的布局
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/image_item_vp" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="fitXY" /> </RelativeLayout>
ImageBean的代码
package com.gtercn.oneday.bean; /** * Created by Administrator on 2016/8/4. */ public class ImageBean { private int imageId; private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public ImageBean(int imageId, String name) { this.imageId = imageId; this.name = name; } public ImageBean(int imageId) { this.imageId = imageId; } public int getImageId() { return imageId; } public void setImageId(int imageId) { this.imageId = imageId; } }
circular_point_shape的布局文件
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval"> <corners android:radius="6dp"/> <stroke android:color="@color/gray12" android:width="1dp"/> <solid android:color="@color/gray12"/> <size android:width="8dp" android:height="8dp"/> </shape>
circular_point_shape_selected的布局文件
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval"> <corners android:radius="6dp"/> <stroke android:color="@color/gray4" android:width="1dp"/> <solid android:color="@color/gray4"/> <size android:width="12dp" android:height="12dp"/> </shape>
效果图