码迷,mamicode.com
首页 > 其他好文 > 详细

fragment和工厂设计模式结合结合

时间:2015-04-14 00:37:31      阅读:1171      评论:0      收藏:0      [点我收藏+]

标签:

	class MyPagerAdapter extends FragmentPagerAdapter{
		private String[] tab_names;
		public MyPagerAdapter(FragmentManager fm) {
			super(fm);
			tab_names = UIUtils.getStringArray(R.array.tab_names);
		}

		@Override
		public Fragment getItem(int arg0) {
			//获取Fragment对应的工厂,如果当前内存中有对象的话,不创建,直接获取
			return FragmentFactory.createFragment(arg0);
		}

		@Override
		public int getCount() {
			return tab_names.length;
		}
		//指针顶部文字
		@Override
		public CharSequence getPageTitle(int position) {
			return tab_names[position];
		}
	}





public class FragmentFactory {
	private static HashMap<Integer,Fragment> hashMap = new HashMap<Integer, Fragment>();
	public static BaseFragment createFragment(int position) {
		BaseFragment baseFragment = null;
		//有对象就获取,没对象就创建
		if(hashMap.containsKey(position)){
			//从缓存中获取对象
			if(hashMap.get(position)!=null){
				baseFragment = (BaseFragment) hashMap.get(position);
			}
		}else{
			//没有对象的时候,创建
			switch (position) {
			case 0:
				baseFragment = new HomeFragment();
				break;
			case 1:
				baseFragment = new AppFragment();
				break;
			case 2:
				baseFragment = new GameFragment();
				break;
			case 3:
				baseFragment = new SubjectFragment();
				break;
			case 4:
				baseFragment = new RecommendFragment();
				break;
			case 5:
				baseFragment = new CategoryFragment();
				break;
			case 6:
				baseFragment = new HotFragment();
				break;
			}
			//缓存到本地
			hashMap.put(position, baseFragment);
		}
		return baseFragment;
	}
}

  

fragment和工厂设计模式结合结合

标签:

原文地址:http://www.cnblogs.com/a454892215/p/4423645.html

(3)
(2)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!