在xml文件中,書寫TabLayout和ViewPager標(biāo)簽
<!-- 和viewpager 結(jié)合的標(biāo)簽 -->
<android.support.design.widget.TabLayout
android:id="@+id/home_tab_"
app:tabBackground="@android:color/transparent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
app:tabMode="scrollable"
app:tabIndicatorHeight="3dp"
app:tabIndicatorColor="@color/pink"
app:tabSelectedTextColor="@color/pink"
app:tabTextColor="#000"
></android.support.design.widget.TabLayout>
<!-- 首頁主內(nèi)容區(qū)域 -->
<android.support.v4.view.ViewPager
android:id="@+id/home_vp_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
ViewPager的適配器
/**
* 首頁frag布局的適配器,
*/
class MyHomeVpContentAdapter extends FragmentStatePagerAdapter {
public MyHomeVpContentAdapter(FragmentManager fm) {
super(fm);
}
// 用來設(shè)置tablayout的標(biāo)簽名
@Override
public CharSequence getPageTitle(int position) {
return tabs[position];
}
@Override
public Fragment getItem(int position) {
switch (position) {
case HOME_POS:
return mHomeTabFragment;
case LIVE_POS:
return mLiveFragment;
case FOLLOW_POS:
return mFollowFragment;
case OTHER_POS:
return mOtherFragment;
}
throw new IllegalStateException("No fragment at position " + position);
}
@Override
public int getCount() {
return tabs.length;
}
}
// viewpager 和 tablayout的結(jié)合
//初始化 viewpager的 adapter
MyHomeVpContentAdapter myHomeVpContentAdapter = new MyHomeVpContentAdapter(getFragmentManager());
//設(shè)置為加載一個(gè)
viewpager.setOffscreenPageLimit(1);
viewpager.setAdapter(myHomeVpContentAdapter);
//tablayout 綁定 viewpager
tablayout.setupWithViewPager(viewpager);
新建Fragment
參考我的另一篇博客.
Activity,Fragment的基類封裝,簡(jiǎn)化findViewById,Fragment懶加載和不重復(fù)加載等