protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); list = new ArrayList<Integer>(); //设置数据 list.add(R.mipmap.ph10); list.add(R.mipmap.ph11); list.add(R.mipmap.ph12); mViewpager.setCurrentItem(list.size()*10000); i = mViewpager.getCurrentItem(); new Thread(){ public void run(){ while (true){ try { sleep(1000); i++; handler.sendEmptyMessage(i); } catch (InterruptedException e) { e.printStackTrace(); } } } }.start(); //创建适配器 ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(list,this); mViewpager.setAdapter(viewPagerAdapter); mViewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { switch (position%list.size()){ case 0: mRadio.check(R.id.button1); break; case 1: mRadio.check(R.id.button2); break; case 2: mRadio.check(R.id.button3); break; } } @Override public void onPageSelected(int position) { } @Override public void onPageScrollStateChanged(int state) { } }); } private void initView() { mButton1 = (RadioButton) findViewById(R.id.button1); mButton2 = (RadioButton) findViewById(R.id.button2); mButton3 = (RadioButton) findViewById(R.id.button3); mRadio = (RadioGroup) findViewById(R.id.radio); mViewpager = (ViewPager) findViewById(R.id.viewpager); }
public class ViewPagerAdapter extends PagerAdapter{ private ArrayList<Integer> list; private Context context; public ViewPagerAdapter(ArrayList<Integer> list, Context context) { this.list = list; this.context = context; } @Override public int getCount() { return Integer.MAX_VALUE; } @Override public boolean isViewFromObject(View view, Object object) { return view==object; } @Override public Object instantiateItem(ViewGroup container, int position) { ImageView imageView = new ImageView(context); imageView.setImageResource(list.get(position%list.size())); imageView.setScaleType(ImageView.ScaleType.FIT_XY); container.addView(imageView); return imageView; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } }