前言:昨晚在做課程設(shè)計(jì)的結(jié)構(gòu)遇到了二級(jí)Fragment(在Fragment里面嵌入了ViewPager)索绪,在數(shù)據(jù)顯示的時(shí)候和媳,如果使用簡單的PagerAdapter的話漆际,代碼在這個(gè)適配器里面會(huì)造成龐大的不好效果械拍,不僅僅如此志于,使用mvp模式涮因,Presenter就會(huì)跑到adapter里面,雖然adapter屬于view圖層恨憎,但是不利于數(shù)據(jù)的處理蕊退。然而我找到了一個(gè)比較推薦的方法:ViewPager使用FragmentPagerAdapter適配器郊楣。FragmentPagerAdapter派生自PagerAdapter,它是用來呈現(xiàn)Fragment頁面的瓤荔。
****適配器實(shí)現(xiàn) - FragmentPagerAdapter****
/**
* Home頁面的適配器adapter
* Created by alic on 16-4-30.
*/
public class HomeFragmentAdapter extends FragmentPagerAdapter{
private List<Fragment> fragmentList = new ArrayList<>();
//構(gòu)造方法一 推薦
public HomeFragmentAdapter(FragmentManager fm) {
super(fm);
this.fragmentList.add(new HomeClassesFragment());
this.fragmentList.add(new HomeAttendanceFragment());
this.fragmentList.add(new HomeExamFragment());
this.fragmentList.add(new HomeGradeFragment());
}
//構(gòu)造方法二
public HomeFragmentAdapter(FragmentManager fm, List<Fragment> fragmentList) {
super(fm);
this.fragmentList = fragmentList;
}
@Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
@Override
public int getCount() {
return fragmentList.size();
}
}
****UI布局實(shí)現(xiàn) - Fragment****
/**
*考試Fragment
* Created by alic on 16-5-8.
*/
public class HomeExamFragment extends Fragment {
private View viewCourse;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
viewCourse = inflater.inflate(R.layout.home_viewpager_three,container, false);
return viewCourse;
}
}
****Activity實(shí)現(xiàn)之二級(jí)Fragment****
//實(shí)例化viewPager
ViewPager viewPager = (ViewPager) parentView.findViewById(R.id.home_main_viewPager);
HomeFragmentAdapter adapter = new HomeFragmentAdapter(getChildFragmentManager());
viewPager.setAdapter(adapter);
****Activity實(shí)現(xiàn)之簡單的activity****
//實(shí)例化viewPager
ViewPager viewPager = (ViewPager) parentView.findViewById(R.id.home_main_viewPager);
HomeFragmentAdapter adapter = new HomeFragmentAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
上面的倆個(gè)Activity實(shí)現(xiàn)的區(qū)別就是前者在Fragment實(shí)現(xiàn)净蚤,后者在Activity實(shí)現(xiàn)
本質(zhì)上就是FragmentManager獲取的方法不一樣前者是通過getChildFragmentManager()獲取,
后者是通過getSupportFragmentManager()獲取输硝。
****注意的問題****
問題1
當(dāng)在this.fragmentList.add(new HomeClassesFragment())可能會(huì)造成無法添加
原因
由于編譯器智能自動(dòng)導(dǎo)包問題造成的今瀑,兩個(gè)類導(dǎo)入的Fragment包不一致
解決
將兩個(gè)Fragment包都導(dǎo)入為ndroid.support.v4.app.Fragment即可