ViewPager无限循环

今天突然一小伙伴问我ViewPager无限循环的问题,在这里我给出demo

package com.example.xuan.viewpager;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity {

    android.support.v4.view.ViewPager pager;

    private List<TextView> textViews;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }


    private void initView() {
        pager = (ViewPager) findViewById(R.id.vp_contains);
        textViews = new ArrayList<TextView>();
        TextView tv;
        for (int i = 0; i < 10; i++) {
            tv = new TextView(this);
            tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,30);
            tv.setTextColor(Color.RED);
            tv.setText("数据:" + i);
            textViews.add(tv);
        }
        pager.setAdapter(new PagerAdapter() {
            @Override
            public int getCount() {
                if (textViews.size() > 1)
                    return Integer.MAX_VALUE;
                return textViews.size();
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                TextView tv = textViews.get(position % textViews.size());
                container.addView(tv);
                return tv;
            }

            @Override
            public boolean isViewFromObject(View view, Object o) {
                return view == o;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView((View) object);
            }
        });
    }
}


你可能感兴趣的:(viewpager,view)