首先是依赖包
compile 'com.android.support:design:23.4.0'
这是要放TabLayout的Fragment
这是Fragment:
public class ZhuyeMyFragment extends Fragment{ private String[] mTitle = new String[4]; private String[] mData = new String[4]; { for(int i=0;i<4;i++) { mTitle[i] = "title" + i; mData[i] = "data" + i; } } TabLayout mTabLayout ; ViewPager mViewPager ; FragmentPagerAdapter mAdapter; Zhuti zt; Zuixin zx; Zl zl; Rm rm; ArrayListflist; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view=inflater.inflate(R.layout.zhuye_layout,null); mTabLayout = (TabLayout)view.findViewById(R.id.tl); mViewPager = (ViewPager)view.findViewById(R.id.viewpager); FragmentManager man = getActivity().getSupportFragmentManager(); initFragment(); flist=new ArrayList (); flist.add(zx); flist.add(zl); flist.add(rm); flist.add(zt); mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); final TabLayout.TabLayoutOnPageChangeListener listener = new TabLayout.TabLayoutOnPageChangeListener(mTabLayout); mViewPager.addOnPageChangeListener(listener); mAdapter= new FragmentAdapter(man,flist); mViewPager.setAdapter(mAdapter); mTabLayout.setTabsFromPagerAdapter(mAdapter); return view; } private void initFragment() { zt=new Zhuti(); zx=new Zuixin(); zl=new Zl(); rm=new Rm(); }}
这是FragmentAdapter:
public class FragmentAdapter extends FragmentPagerAdapter { private String [] title = { "最新日报","热门","专栏","主题日报"}; private ListfragmentList; public FragmentAdapter(FragmentManager fm, List fragmentList) { super(fm); this.fragmentList = fragmentList; } @Override public Fragment getItem(int position) { return fragmentList.get(position); } @Override public int getCount() { return fragmentList.size(); } @Override public CharSequence getPageTitle(int position) { return title[position]; }}