ViewPager的功能就是可以使视图滑动,就像Lanucher左右滑动那样。分三个步骤来使用它:
1.在住布局文件里加入
<android.support.v4.view.ViewPager
android:id="@+id/guidePages"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
2.加载要显示的页卡---将要分页显示的View装入数组中
LayoutInflater inflater = getLayoutInflater();
List<View> pageViews = new ArrayList<View>();
pageViews.add(inflater.inflate(R.layout.item05, null));
pageViews.add(inflater.inflate(R.layout.item06, null));
pageViews.add(inflater.inflate(R.layout.item01, null));
pageViews.add(inflater.inflate(R.layout.item02, null));
pageViews.add(inflater.inflate(R.layout.item03, null));
pageViews.add(inflater.inflate(R.layout.item04, null));
3.在Activity里实例化ViewPager组件,并设置它的Adapter(就是PagerAdapter,方法与ListView一样的),在这里一般需要重写PagerAdapter。
//实例化ViewPager
viewPager = (ViewPager)main.findViewById(R.id.guidePages);
//设置它的Adapter
viewPager.setAdapter(new GuidePageAdapter());
viewPager.setOnPageChangeListener(new GuidePageChangeListener());
// 指引页面数据适配器
class GuidePageAdapter extends PagerAdapter {
@Override
public int getCount() {
return pageViews.size();
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
@Override
public int getItemPosition(Object object) {
// TODO Auto-generated method stub
return super.getItemPosition(object);
}
@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
// TODO Auto-generated method stub
((ViewPager) arg0).removeView(pageViews.get(arg1));
}
@Override
public Object instantiateItem(View arg0, int arg1) {
// TODO Auto-generated method stub
((ViewPager) arg0).addView(pageViews.get(arg1));
return pageViews.get(arg1);
}
@Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {
// TODO Auto-generated method stub
}
@Override
public Parcelable saveState() {
// TODO Auto-generated method stub
return null;
}
@Override
public void startUpdate(View arg0) {
// TODO Auto-generated method stub
}
@Override
public void finishUpdate(View arg0) {
// TODO Auto-generated method stub
}
}
// 指引页面更改事件监听器
class GuidePageChangeListener implements OnPageChangeListener {
@Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
@Override
public void onPageSelected(int arg0) {
for (int i = 0; i < imageViews.length; i++) {
imageViews[arg0].setBackgroundResource(R.drawable.page_indicator_focused);
if (arg0 != i) {
imageViews[i].setBackgroundResource(R.drawable.page_indicator);
}
}
}
}