本文实例为大家分享了android手动和自动轮播图效果的具体代码,供大家参考,具体内容如下
1、准备好需要的轮播图片,图片标题(初始化,声明)。
/**轮播图片*/ private int[] imageIds=new int[]{ R.drawable.ic_launcher, R.drawable.simple_player_control_focused_holo, R.drawable.dot_player1_1, R.drawable.jt5, }; /**轮播图片的标题*/ private String[] titles=new String[]{ "我是一", "我是二", "我是三", "我是四", };
2、在你要轮播的布局里面加入下面的布局(相当于加入一个控件,看你想放哪里).
3、把图片和标题都设置控件里面。
/**显示的图片*/ images = new ArrayList(); for(int i=0;i (); dots.add(view.findViewById(R.id.dot_0)); dots.add(view.findViewById(R.id.dot_1)); dots.add(view.findViewById(R.id.dot_2)); dots.add(view.findViewById(R.id.dot_3)); /**轮播的标题*/ title = (TextView) view.findViewById(R.id.title); title.setText(titles[0]);
4、findViewById到控件布局里面的ViewPager,new 一个ViewpagerAdapter(),通过setOnPageChangeListener的方法来监听改变
viewPager = (ViewPager) view.findViewById(R.id.viewPager); adapter = new ViewPagerAdapter(); viewPager.setAdapter(adapter); viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { title.setText(titles[position]); dots.get(position).setBackgroundResource(R.drawable.dot_focused); dots.get(oldPosition).setBackgroundResource(R.drawable.dot_normal); oldPosition = position; currentItem = position; } @Override public void onPageSelected(int position) { } @Override public void onPageScrollStateChanged(int state) { } });
5、自定义一个ViewPagerAdapter
/** * 自定义Adapter * 内部类 */ private class ViewPagerAdapter extends PagerAdapter { @Override public int getCount() { return images.size();//传入的数据 } @Override public boolean isViewFromObject(View arg0, Object arg1) { return arg0 == arg1; } @Override public void destroyItem(ViewGroup view, int position, Object object) { // TODO Auto-generated method stub // super.destroyItem(container, position, object); // view.removeView(view.getChildAt(position)); // view.removeViewAt(position); view.removeView(images.get(position)); } @Override public Object instantiateItem(ViewGroup view, int position) { // TODO Auto-generated method stub view.addView(images.get(position)); return images.get(position); } }
6、这些自己看着改主要是线程池,handler,定时轮换
/** * 图片轮播任务 * */ private class ViewPageTask implements Runnable{ @Override public void run() { currentItem = (currentItem + 1) % imageIds.length; mHandler.sendEmptyMessage(0); } } /** * 接收子线程传递过来的数据 */ private Handler mHandler = new Handler(){ public void handleMessage(android.os.Message msg) { viewPager.setCurrentItem(currentItem); }; }; @Override public void onStop() { // TODO Auto-generated method stub super.onStop(); if(scheduledExecutorService != null){ scheduledExecutorService.shutdown(); scheduledExecutorService = null; } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。