废话不多说了,先给大家上左右无限滑动的代码了。
1.左右无限滑动
public class MainActivity extends AppCompatActivity {private static ViewPager viewPager;private RadioGroup group;//图片资源,实际项目需要从网络获取private int[] imageIds = {R.drawable.ym1, R.drawable.ym2, R.drawable.ym3, R.drawable.ym4};//存放图片的数组private List<ImageView> mList;//当前索引位置以及上一个索引位置private static int index = 0, preIndex = 0;//是否需要轮播标志private boolean isContinue = true;//定时器,用于实现轮播private Timer timer = new Timer();private MyHandler mHandler;public static class MyHandler extends Handler {private WeakReference<MainActivity> weakReference;public MyHandler(MainActivity activity) {weakReference = new WeakReference<>(activity);}@Overridepublic void handleMessage(Message msg) {if (weakReference.get() != null) {index++;viewPager.setCurrentItem(index);}super.handleMessage(msg);}}@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initView();initData();addListener();//让当前图片位于中间某个位置,目的就是为了开始能够左滑viewPager.setCurrentItem(imageIds.length * 100);initRadioButton(imageIds.length);//注意这句和上面那句顺序不能写反,否则会出现第一个圆点无法显示选中状态startSwitch();}/*** 初始化控件*/public void initView() {viewPager = (ViewPager) findViewById(R.id.viewpager);group = (RadioGroup) findViewById(R.id.group);}/*** 初始化数据*/public void initData() {mList = new ArrayList<>();viewPager.setAdapter(pagerAdapter);mHandler = new MyHandler(this);}/*** 添加监听*/public void addListener() {viewPager.addOnPageChangeListener(onPageChangeListener);viewPager.setOnTouchListener(onTouchListener);}/*** 进行图片轮播*/public void startSwitch() {//执行定时任务timer.schedule(new TimerTask() {@Overridepublic void run() {//首先判断是否需要轮播,是的话我们才发消息if (isContinue) {mHandler.sendEmptyMessage(1);}}}, 3000, 3500);//延迟3秒,每隔3.5秒发一次消息;}/*** 根据图片个数初始化按钮* @param length 图片所在集合长度*/private void initRadioButton(int length) {for (int i = 0; i < length; i++) {ImageView imageview = new ImageView(this);imageview.setImageResource(R.drawable.rg_selector);//设置背景选择器imageview.setPadding(20, 0, 0, 0);//设置每个按钮之间的间距//将按钮依次添加到RadioGroup中group.addView(imageview, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);//默认选中第一个按钮,因为默认显示第一张图片group.getChildAt(0).setEnabled(false);}}/*** 根据当前触摸事件判断是否要轮播*/View.OnTouchListener onTouchListener = new View.OnTouchListener() {@Overridepublic boolean onTouch(View v, MotionEvent event) {switch (event.getAction()) {//手指按下和划动的时候停止图片的轮播case MotionEvent.ACTION_DOWN:case MotionEvent.ACTION_MOVE:isContinue = false;break;default:isContinue = true;}return false;//注意这里只能返回false,如果返回true,Dwon就会消费掉事件,MOVE无法获得事件,// 导致图片无法滑动}};/*** 根据当前选中的页面设置按钮的选中*/ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {@Overridepublic void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}@Overridepublic void onPageSelected(int position) {index = position;//当前位置赋值给索引setCurrentDot(index % imageIds.length);//因为只有四个按钮,所以我们在此要对长度区域,保证范围在0到4}@Overridepublic void onPageScrollStateChanged(int state) {}};/*** 设置对应位置按钮的状态* @param i 当前位置*/private void setCurrentDot(int i) {if (group.getChildAt(i) != null) {group.getChildAt(i).setEnabled(false);//当前按钮选中,显示蓝色}if (group.getChildAt(preIndex) != null) {group.getChildAt(preIndex).setEnabled(true);//上一个取消选中。显示灰色preIndex = i;//当前位置变为上一个,继续下次轮播}}PagerAdapter pagerAdapter = new PagerAdapter() {@Overridepublic int getCount() {//返回一个比较大的值,目的是为了实现无限轮播return Integer.MAX_VALUE;}@Overridepublic boolean isViewFromObject(View view, Object object) {return view == object;}@Overridepublic Object instantiateItem(ViewGroup container, int position) {position = position % imageIds.length;//因为position非常大,而我们需要的position不能大于图片集合长度//所以在此取余ImageView imageView = new ImageView(MainActivity.this);imageView.setImageResource(imageIds[position]);imageView.setScaleType(ImageView.ScaleType.FIT_XY);container.addView(imageView);mList.add(imageView);return imageView;}@Overridepublic void destroyItem(ViewGroup container, int position, Object object) {// 注意在此不要做任何操作,因为我们需要实现向左滑动,否则会产生IndexOutOfBoundsException}};@Overrideprotected void onDestroy() {super.onDestroy();//页面销毁的时候取消定时器if (timer != null) {preIndex = 0;timer.cancel();}}}
2.单向滑动
public class MainActivity extends AppCompatActivity {private static ViewPager viewPager;private RadioGroup group;//图片资源,实际项目需要从网络获取private int[] imageIds = {R.drawable.ym1, R.drawable.ym2, R.drawable.ym3, R.drawable.ym4};//存放图片的数组private List<ImageView> mList;//当前索引位置以及上一个索引位置private static int index = 0, preIndex = 0;//是否需要轮播标志private boolean isContinue = true;//定时器,用于实现轮播private Timer timer = new Timer();private MyHandler mHandler;public static class MyHandler extends Handler {private WeakReference<MainActivity> weakReference;public MyHandler(MainActivity activity) {weakReference = new WeakReference<>(activity);}@Overridepublic void handleMessage(Message msg) {if (weakReference.get() != null) {index++;viewPager.setCurrentItem(index);}super.handleMessage(msg);}}@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initView();initData();addListener();initRadioButton(imageIds.length);startSwitch();}/*** 初始化控件*/public void initView() {viewPager = (ViewPager) findViewById(R.id.viewpager);group = (RadioGroup) findViewById(R.id.group);}/*** 初始化数据*/public void initData() {mList = new ArrayList<>();viewPager.setAdapter(pagerAdapter);mHandler = new MyHandler(this);}/*** 添加监听*/public void addListener() {viewPager.addOnPageChangeListener(onPageChangeListener);viewPager.setOnTouchListener(onTouchListener);}/*** 进行图片轮播*/public void startSwitch() {//执行定时任务timer.schedule(new TimerTask() {@Overridepublic void run() {//首先判断是否需要轮播,是的话我们才发消息if (isContinue) {mHandler.sendEmptyMessage(1);}}}, 3000, 3500);//延迟3秒,每隔3.5秒发一次消息;}/*** 根据图片个数初始化按钮* @param length 图片所在集合长度*/private void initRadioButton(int length) {for (int i = 0; i < length; i++) {ImageView imageview = new ImageView(this);imageview.setImageResource(R.drawable.rg_selector);//设置背景选择器imageview.setPadding(20, 0, 0, 0);//设置每个按钮之间的间距//将按钮依次添加到RadioGroup中group.addView(imageview, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);//默认选中第一个按钮,因为默认显示第一张图片group.getChildAt(0).setEnabled(false);}}/*** 根据当前触摸事件判断是否要轮播*/View.OnTouchListener onTouchListener = new View.OnTouchListener() {@Overridepublic boolean onTouch(View v, MotionEvent event) {switch (event.getAction()) {//手指按下和划动的时候停止图片的轮播case MotionEvent.ACTION_DOWN:case MotionEvent.ACTION_MOVE:isContinue = false;break;default:isContinue = true;}return false;//注意这里只能返回false,如果返回true,Dwon就会消费掉事件,MOVE无法获得事件,// 导致图片无法滑动}};/*** 根据当前选中的页面设置按钮的选中*/ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {@Overridepublic void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}@Overridepublic void onPageSelected(int position) {index = position;//当前位置赋值给索引setCurrentDot(index % imageIds.length);//因为只有四个按钮,所以我们在此要对长度区域,保证范围在0到4}@Overridepublic void onPageScrollStateChanged(int state) {}};/*** 设置对应位置按钮的状态* @param i 当前位置*/private void setCurrentDot(int i) {if (group.getChildAt(i) != null) {group.getChildAt(i).setEnabled(false);//当前按钮选中,显示蓝色}if (group.getChildAt(preIndex) != null) {group.getChildAt(preIndex).setEnabled(true);//上一个取消选中。显示灰色preIndex = i;//当前位置变为上一个,继续下次轮播}}PagerAdapter pagerAdapter = new PagerAdapter() {@Overridepublic int getCount() {//返回一个比较大的值,目的是为了实现无限轮播return Integer.MAX_VALUE;}@Overridepublic boolean isViewFromObject(View view, Object object) {return view == object;}@Overridepublic Object instantiateItem(ViewGroup container, int position) {position = position % imageIds.length;//因为position非常大,而我们需要的position不能大于图片集合长度//所以在此取余ImageView imageView = new ImageView(MainActivity.this);imageView.setImageResource(imageIds[position]);imageView.setScaleType(ImageView.ScaleType.FIT_XY);container.addView(imageView);mList.add(imageView);return imageView;}@Overridepublic void destroyItem(ViewGroup container, int position, Object object) {container.removeView(mList.get(position));}};@Overrideprotected void onDestroy() {super.onDestroy();//页面销毁的时候取消定时器if (timer != null) {preIndex = 0;index = 0;timer.cancel();}}}
3.加入一张图片的判断(最终版)
public class MainActivity extends AppCompatActivity {private static ViewPager viewPager;private RadioGroup group;//图片资源,实际项目需要从网络获取// private int[] imageIds = {R.drawable.ym1, R.drawable.ym2, R.drawable.ym3, R.drawable.ym4};private int[] imageIds = {R.drawable.ym1};//存放图片的数组private List<ImageView> mList;//当前索引位置以及上一个索引位置private static int index = 0, preIndex = 0;//是否需要轮播标志private boolean isContinue = true;//定时器,用于实现轮播private Timer timer = new Timer();private MyHandler mHandler;public static class MyHandler extends Handler {private WeakReference<MainActivity> weakReference;public MyHandler(MainActivity activity) {weakReference = new WeakReference<>(activity);}@Overridepublic void handleMessage(Message msg) {if (weakReference.get() != null) {index++;viewPager.setCurrentItem(index);}super.handleMessage(msg);}}@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initView();initData();addListener();initRadioButton(imageIds.length);//注意这句和上面那句顺序不能写反,否则会出现第一个圆点无法显示选中状态startSwitch();}/*** 初始化控件*/public void initView() {viewPager = (ViewPager) findViewById(R.id.viewpager);group = (RadioGroup) findViewById(R.id.group);}/*** 初始化数据*/public void initData() {mList = new ArrayList<>();viewPager.setAdapter(pagerAdapter);mHandler = new MyHandler(this);}/*** 添加监听*/public void addListener() {viewPager.addOnPageChangeListener(onPageChangeListener);viewPager.setOnTouchListener(onTouchListener);}/*** 进行图片轮播*/public void startSwitch() {//执行定时任务timer.schedule(new TimerTask() {@Overridepublic void run() {//首先判断是否需要轮播,是的话我们才发消息if (isContinue) {if(imageIds.length!=1)//多于一张图片才轮播mHandler.sendEmptyMessage(1);}}}, 3000, 3500);//延迟3秒,每隔3.5秒发一次消息;}/*** 根据图片个数初始化按钮* @param length 图片所在集合长度*/private void initRadioButton(int length) {for (int i = 0; i < length; i++) {ImageView imageview = new ImageView(this);if(length == 1){imageview.setVisibility(View.GONE);return;}imageview.setImageResource(R.drawable.rg_selector);//设置背景选择器imageview.setPadding(20, 0, 0, 0);//设置每个按钮之间的间距//将按钮依次添加到RadioGroup中group.addView(imageview, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);//默认选中第一个按钮,因为默认显示第一张图片group.getChildAt(0).setEnabled(false);}}/*** 根据当前触摸事件判断是否要轮播*/View.OnTouchListener onTouchListener = new View.OnTouchListener() {@Overridepublic boolean onTouch(View v, MotionEvent event) {switch (event.getAction()) {//手指按下和划动的时候停止图片的轮播case MotionEvent.ACTION_DOWN:case MotionEvent.ACTION_MOVE:isContinue = false;break;default:isContinue = true;}if(imageIds.length == 1){return true;//1张图片不允许滑动}return false;//注意这里只能返回false,如果返回true,Dwon就会消费掉事件,MOVE无法获得事件,// 导致图片无法滑动}};/*** 根据当前选中的页面设置按钮的选中*/ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {@Overridepublic void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}@Overridepublic void onPageSelected(int position) {index = position;//当前位置赋值给索引setCurrentDot(index % imageIds.length);//因为只有四个按钮,所以我们在此要对长度区域,保证范围在0到4}@Overridepublic void onPageScrollStateChanged(int state) {}};/*** 设置对应位置按钮的状态* @param i 当前位置*/private void setCurrentDot(int i) {if (group.getChildAt(i) != null) {group.getChildAt(i).setEnabled(false);//当前按钮选中,显示蓝色}if (group.getChildAt(preIndex) != null) {group.getChildAt(preIndex).setEnabled(true);//上一个取消选中。显示灰色preIndex = i;//当前位置变为上一个,继续下次轮播}}PagerAdapter pagerAdapter = new PagerAdapter() {@Overridepublic int getCount() {//返回一个比较大的值,目的是为了实现无限轮播return Integer.MAX_VALUE;}@Overridepublic boolean isViewFromObject(View view, Object object) {return view == object;}@Overridepublic Object instantiateItem(ViewGroup container, int position) {position = position % imageIds.length;//因为position非常大,而我们需要的position不能大于图片集合长度//所以在此取余ImageView imageView = new ImageView(MainActivity.this);imageView.setImageResource(imageIds[position]);imageView.setScaleType(ImageView.ScaleType.FIT_XY);container.addView(imageView);mList.add(imageView);return imageView;}@Overridepublic void destroyItem(ViewGroup container, int position, Object object) {// 注意在此不要做任何操作,因为我们需要实现向左滑动,否则会产生IndexOutOfBoundsExceptioncontainer.removeView(mList.get(position));}};@Overrideprotected void onDestroy() {super.onDestroy();//页面销毁的时候取消定时器if (timer != null) {preIndex = 0;index = 0;timer.cancel();}}}
以上所述是小编给大家介绍的Android实现图片自动轮播并且支持手势左右无限滑动,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!
新闻热点
疑难解答