适配器
public class MyAdapter extends PagerAdapter { ArrayList<ImageView> imageViews; Context context; public MyAdapter(ArrayList<ImageView> imageViews, Context context) { this.imageViews = imageViews; this.context = context; } @Override public int getCount() { return imageViews.size(); } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView(imageViews.get(position)); } @Override public Object instantiateItem(ViewGroup container, int position) { container.addView(imageViews.get(position)); return imageViews.get(position); } }核心代码
public class MainActivity extends AppCompatActivity { private ViewPager viewPager; int[] image = {R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher}; ArrayList<ImageView> imageViews = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); initData(); initAdapter(); initLin(); } private void initAdapter() { MyAdapter myAdapter = new MyAdapter(imageViews,this); viewPager.setAdapter(myAdapter); } private void initLin() { viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { if (position==2){ Intent intent = new Intent(MainActivity.this,Main2Activity.class); startActivity(intent); } } @Override public void onPageScrollStateChanged(int state) { } }); } private void initData() { for (int i = 0; i < 3; i++) { ImageView imageView = new ImageView(MainActivity.this); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setImageResource(image[i]); imageViews.add(imageView); } } private void initView() { viewPager = (ViewPager) findViewById(R.id.viewpager); } }
布局
<android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="match_parent" ></android.support.v4.view.ViewPager>