Android_ViewPager_ViewPager使用详解及相应的adapter适配器

1.ViewPager事件

ViewPager通常和Fragment配合一起使用,能够使用适当的方式去管理每一页的生命周期,并使用PagerAdapter去生成每一页显示的view数据,向左向右可以滑出每页视图。

OnPageChangeListener{
	/**
	 * This method will be invoked when the current page is scrolled, either as
	 * part of a programmatically initiated smooth scroll or a user initiated
	 * touch scroll.
	 * 
	 * @param position
	 *            Position index of the first page currently being displayed.
	 *            Page position+1 will be visible if positionOffset is nonzero.
	 * @param positionOffset
	 *            Value from [0, 1) indicating the offset from the page at
	 *            position.
	 * @param positionOffsetPixels
	 *            Value in pixels indicating the offset from position.
	 */
	public void onPageScrolled(int position, float positionOffset,
			int positionOffsetPixels) {
	}

	/**
	 * This method will be invoked when a new page becomes selected. Animation
	 * is not necessarily complete.
	 * 
	 * @param position
	 *            Position index of the new selected page.
	 */
	// 一个新页被调用时执行,仍为原来的page时,该方法不被调用
	public void onPageSelected(int position) {
		for (int i = 0; i < imageViews.length; i++) {
			imageViews[position]
					.setBackgroundResource(R.drawable.guide_dot_green);
			if (position != i) {
				imageViews[i]
						.setBackgroundResource(R.drawable.guide_dot_normal);
			}
		}
	}

	/**
	 * Called when the scroll state changes. Useful for discovering when the
	 * user begins dragging, when the pager is automatically settling to the
	 * current page, or when it is fully stopped/idle.
	 * 
	 * @param state
	 *            The new scroll state.
	 * @see ViewPager#SCROLL_STATE_IDLE
	 * @see ViewPager#SCROLL_STATE_DRAGGING
	 * @see ViewPager#SCROLL_STATE_SETTLING
	 */
	/*
	 * SCROLL_STATE_IDLE: pager处于空闲状态 
	 * SCROLL_STATE_DRAGGING: pager处于正在拖拽中
	 * SCROLL_STATE_SETTLING: pager正在自动沉降,相当于松手后,pager恢复到一个完整pager的过程
	 */
	public void onPageScrollStateChanged(int state) {
		// System.out.println("state:" + state);

	}
	/*
	 * { private void setScrollState(int newState) { // ...
	 * if(mOnPageChangeListener != null) {
	 * mOnPageChangeListener.onPageScrollStateChanged(newState);//调用 } }
	 */
}

2.PagerAdapter

//PagerAdapter是object的子类
class MyAdapter extends PagerAdapter {

	/**
	 * PagerAdapter管理数据大小
	 */
	@Override
	public int getCount() {
		return views.size();
	}

	/**
	 * 关联key 与 obj是否相等,即是否为同一个对象
	 */
	@Override
	public boolean isViewFromObject(View view, Object obj) {
		return view == obj; // key
	}

	/**
	 * 销毁当前page的相隔2个及2个以上的item时调用
	 */
	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {
		container.removeView((View) object); // 将view 类型 的object熊容器中移除,根据key
	}

	/**
	 * 当前的page的前一页和后一页也会被调用,如果还没有调用或者已经调用了destroyItem
	 */
	@Override
	public Object instantiateItem(ViewGroup container, int position) {
		container.addView(views.get(position));
		return views.get(position); // 返回该view对象,作为key
	}
}

3.FragmentPagerAdapter

用户访问的每页数据都保存在内存中,因此适合访问页数不是很多的情况!使用至需要复写getItem(int) and getCount()方法,如果页数很多可以使用FragmentStatePagerAdapter,通过bundle保存每页的状态信息,因而占用内存就很小。

Android_ViewPager_ViewPager使用详解及相应的adapter适配器_第1张图片                        Android_ViewPager_ViewPager使用详解及相应的adapter适配器_第2张图片

public class MainActivity extends FragmentActivity implements TabListener,
		OnPageChangeListener {

	private ActionBar actionBar;
	private final static int TYPE_YULE = 0;
	private final static int TYPE_NEWS = 1;
	private final static int TYPE_SPORT = 2;

	private static List<Fragment> fragments;
	private ViewPager viewPager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		viewPager = (ViewPager) findViewById(R.id.container);
		actionBar = getActionBar();
		fragments = new ArrayList<Fragment>();
		fragments.add(new YuleFragment());
		fragments.add(new NewsFragment());
		fragments.add(new SportFragment());

		// actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.appmgr_btn_upgrade_selected));
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		actionBar.addTab(actionBar.newTab().setText("娱乐").setTag(TYPE_YULE)
				.setTabListener(this));
		actionBar.addTab(actionBar.newTab().setText("新闻").setTag(TYPE_NEWS)
				.setTabListener(this));
		actionBar.addTab(actionBar.newTab().setText("体育").setTag(TYPE_SPORT)
				.setTabListener(this));

		viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
		viewPager.setOnPageChangeListener(this);

	}

	private static class MyAdapter extends FragmentPagerAdapter {// static

		public MyAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			return fragments.get(position);
		}

		@Override
		public int getCount() {
			return fragments.size();
		}
	}

	@Override
	public void onTabSelected(Tab tab, FragmentTransaction ft) {
		int tag = Integer.parseInt(tab.getTag().toString());
		//设置当前的viewpager的当前viewItem
		viewPager.setCurrentItem(tag);
	}

	@Override
	public void onPageSelected(int position) {
		//滑动时设置actionbar的当前tab
		actionBar.setSelectedNavigationItem(position);
	}

	@Override
	public void onPageScrollStateChanged(int state) {
	}

	@Override
	public void onTabUnselected(Tab tab, FragmentTransaction ft) {
	}

	@Override
	public void onTabReselected(Tab tab, FragmentTransaction ft) {
	}

	@Override
	public void onPageScrolled(int position, float positionOffset,
			int positionOffsetPixels) {
	}
}

4.FragmentStatePagerAdapter

当有大量页数时,使用该类型的适配器很合适,类似于listview,当页面不在可见,fragment对象有可能销毁,但是,这些fragment的状态信息被保存下来,类似于activity的状态保存,从而占用很少的内存。用法与FragmentPagerAdapter 类似

你可能感兴趣的:(android,viewpager,Actionbar,PagerAdapter,FragmentManager)