<code><code><code><code><code> public class MainActivity extends Activity {
protected static final String tag = "MainActivity" ;
private ViewPager viewpager;
private List<imageview> imageList = new ArrayList<imageview>();
private Context context;
int msgWhat = 0 ;
private Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
viewpager.setCurrentItem(viewpager.getCurrentItem() + 1 ); //收到消息,指向下一個(gè)頁面
handler.sendEmptyMessageDelayed(msgWhat, 2000 ); //2S后在發(fā)送一條消息,由于在handleMessage()方法中,造成死循環(huán)。
Log.d(tag, "handleMessage" );
};
};
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this ;
initData();
viewpager = (ViewPager) findViewById(R.id.viewpager);
viewpager.setAdapter( new MyAdapter());
viewpager.setCurrentItem( 1000 ); //當(dāng)前頁是第1000頁
// Button只是為了驗(yàn)證內(nèi)存泄露
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, SecondActivity. class );
startActivity(intent);
}
});
}
private void initData() {
imageList.clear();
ImageView iva = new ImageView(context);
iva.setBackgroundResource(R.drawable.a);
ImageView ivb = new ImageView(context);
ivb.setBackgroundResource(R.drawable.b);
ImageView ivc = new ImageView(context);
ivc.setBackgroundResource(R.drawable.c);
ImageView ivd = new ImageView(context);
ivd.setBackgroundResource(R.drawable.d);
ImageView ive = new ImageView(context);
ive.setBackgroundResource(R.drawable.e);
imageList.add(iva);
imageList.add(ivb);
imageList.add(ivc);
imageList.add(ivd);
imageList.add(ive);
}
public class MyAdapter extends PagerAdapter{
//表示viewpager共存放了多少個(gè)頁面
@Override
public int getCount() {
return Integer.MAX_VALUE; //我們設(shè)置viewpager中有Integer.MAX_VALUE個(gè)頁面
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
/**
* position % imageList.size() 而不是position,是為了防止角標(biāo)越界異常
* 因?yàn)槲覀冊O(shè)置了viewpager子頁面的數(shù)量有Integer.MAX_VALUE,而imageList的數(shù)量只是5。
*/
@Override
public Object instantiateItem(ViewGroup container, int position) {
container.addView(imageList.get(position % imageList.size()));
return imageList.get(position % imageList.size());
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View)object);
}
}
/**
* activity可見可交互的時(shí)候就開始發(fā)送消息,開啟循環(huán)
*/
@Override
protected void onResume() {
super .onResume();
handler.sendEmptyMessageDelayed(msgWhat, 2000 );
}
/**
* 當(dāng)MainActivity不可見的時(shí)候讓handler停止發(fā)送消息
* 防止內(nèi)存泄露
*/
@Override
protected void onStop() {
super .onStop();
handler.removeMessages(msgWhat);
}
}</imageview></imageview></code></code></code></code></code>
|