Android中轮播图的实现


在Android中想要实现轮播图,会用到ViewPager和其子控件PagerTabStrip(标题栏)

怎么样一步一步的去做到:

1.将View视图添加到集合中

public class MyActivity extends Activity{

    ViewPager viewPager;
    View view_a,view_b,view_c;
    List viewList;
    PagerTabStrip pts;
    ArrayListarrayList_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);
viewList = new ArrayList();
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("第三页");
        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);


2.创建数据源Adapter,传入到集合,并且要实现其中的四个方法 

a. getCount() 获取数据源的大小 b. isViewFromObject() 判断当前的View是否是对对象返回 c. instantiateItem() 初始换页面  d. destroyItem() 销毁页面


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));   
 }


虽然很是粗糙,但是将就看看吧! 下面是具体的实现效果


Android中轮播图的实现_第1张图片


你可能感兴趣的:(Android中轮播图的实现)