import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
private static final int AUTO_SCROLL = 0;
ArrayList<View> viewList = new ArrayList<View>();
private ViewPager viewPager;
private LinearLayout ll;
Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
if(msg.what==AUTO_SCROLL){
// 获取当前viewPager所在索引值
int currentItem = viewPager.getCurrentItem();
// 让索引++
currentItem++;
// 重新设置viewPager
viewPager.setCurrentItem(currentItem);
handler.sendEmptyMessageDelayed(AUTO_SCROLL, 2000);
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 找控件
viewPager = (ViewPager) findViewById(R.id.viewPager);
// 初始化View
initView();
// 设置适配器
viewPager.setAdapter(new MyPagerAdapter(viewList));
// 无限轮播
viewPager.setCurrentItem(10000*viewList.size());
// 自动
handler.sendEmptyMessageDelayed(AUTO_SCROLL, 2000);
}
// 移除所有的回调消息
@Override
protected void onDestroy() {
handler.removeCallbacksAndMessages(null);
super.onDestroy();
}
// 加载图片的方法
private void initView() {
// 分别将每一项要展示的view添加到集合中
View view1 = View.inflate(this, R.layout.vp1, null);
View view2 = View.inflate(this, R.layout.vp2, null);
View view3 = View.inflate(this, R.layout.vp3, null);
View view4 = View.inflate(this, R.layout.vp4, null);
viewList.add(view1);
viewList.add(view2);
viewList.add(view3);
viewList.add(view4);
}
}
/*****************************适配器
import java.util.ArrayList;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
public class MyPagerAdapter extends PagerAdapter {
private ArrayList<View> viewList;
public MyPagerAdapter(ArrayList<View> viewList) {
this.viewList = viewList;
}
// 要展示的view个数
@Override
public int getCount() {
return Integer.MAX_VALUE;
}
/**
* 将view添加到容器中
* 返回一个与view对应的key
*/
// 实例化view 并添加到容器中
@Override
public Object instantiateItem(ViewGroup container, int position) {
// 丛集合中根据索引获取当前要展示的视图
View view = viewList.get(position%viewList.size());
// 将view添加到容器中
container.addView(view);
return view;
}
/**
* 当前的视图是否和instantItem所返回key对应的view是否一致
*/
@Override
public boolean isViewFromObject(View view, Object object) {
return view==object;
}
/**
* 销毁条目
* object 看instantiateItem所返回的是不是view 如果是,可以直接移除object
*/
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
// super.destroyItem(container, position, object);
// 从容器中移除所添加的条目
//container.removeView(viewList.get(position));
container.removeView((View) object);
}
}