在Android中想要实现轮播图,会用到ViewPager和其子控件PagerTabStrip(标题栏)
步骤:
1.将View视图添加进集合中去 创建数据源Adapter 并实现其中的四个方法
a.getCount() 获取数据源的大小
b. isViewFromObject() 判断当前的View是否是对对象返回
c. instantiateItem() 初始换页面
d. destroyItem() 销毁页面
public class MyActivity extends Activity{ ViewPager viewPager; View view_a,view_b,view_c; List<View> viewList; PagerTabStrip pts; ArrayList<String>arrayList_pts; Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity); pts = (PagerTabStrip) findViewById(R.id.pts); pts.setBackgroundColor(Color.parseColor("#FF8EFF")); pts.setTabIndicatorColor(Color.parseColor("#00FFFF")); viewPager = (ViewPager) findViewById(R.id.vp_activity); LayoutInflater inflater = LayoutInflater.from(this); view_a = inflater.inflate(R.layout.activity_one,null); view_b = inflater.inflate(R.layout.activity_two,null); view_c = inflater.inflate(R.layout.activity_three,null); button = (Button) view_c.findViewById(R.id.but_three_a); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent1 = new Intent(); intent1.setClass(MyActivity.this,MyActivity_Button.class); startActivity(intent1); } }); viewList = new ArrayList<View>(); viewList.add(view_a); viewList.add(view_b); viewList.add(view_c); arrayList_pts = new ArrayList<>(); arrayList_pts.add("第一页"); arrayList_pts.add("第二页"); arrayList_pts.add("第三页"); PagerAdapter pagerAdapter = new PagerAdapter() { @Override public int getCount() { return viewList.size(); } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public Object instantiateItem(ViewGroup container, int position) { container.addView(viewList.get(position)); return viewList.get(position); } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView(viewList.get(position)); } @Override public CharSequence getPageTitle(int position) { return arrayList_pts.get(position); } }; viewPager.setAdapter(pagerAdapter);
/**ViewPager的监听事件**/ viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { /**滑动时调用*/ @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } /**停止时调用**/ @Override public void onPageSelected(int position) { } /**滑动状态改变的时候调用*/ @Override public void onPageScrollStateChanged(int state) { } }); } }
在其中添加了ViewPager的子控件PagerTabStrip来显示页数,随页面切换来改变,最后一夜的Button是跳转到新的页面。
至于其自动的滑动还没实现,主要是依靠线程sleep来实现
下面是一个粗糙的实现图