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; } }
时间: 2024-11-02 13:29:18