TabLayout+ViewPager结合使用
2018-03-18 本文已影响0人
强0808
1.布局的写法
<LinearLayout
android:id="@+id/tab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/black_alpha_5"
android:orientation="vertical">
<LinearLayout
android:id="@+id/status_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="46dp"
app:tabIndicatorColor="@color/tab_selected_line_def"
app:tabSelectedTextColor="@color/tab_text_selected_def"
app:tabTextColor="@color/tab_text_normal_def"
app:tabTextAppearance="@style/CustomTabLayoutTextAppearance"
/>
</LinearLayout>
<android.support.v4.view.ViewPager
android:id="@+id/main_viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
2.Activity的写法
@BindView(R.id.status_bar)
LinearLayout statusBar;
@BindView(R.id.tab_layout)
TabLayout tabLayout;
@BindView(R.id.main_viewpager)
ViewPager mainViewPager;
//viewPager的适配器
private FixPagerAdapter fixPagerAdapter;
private String[] titles={"推荐","分类","排行","管理","我的"};
private List<Fragment> fragments;
//对fragment进行绑定
private void intViewPagerFragment() {
fixPagerAdapter=new FixPagerAdapter(getSupportFragmentManager());
fragments=new ArrayList<>();
for(int i=0;i<titles.length;i++){
// new RecommendFragment();
//
fragments.add(FragmentFactory.createFragment(i));
}
fixPagerAdapter.setTitles(titles);
fixPagerAdapter.setFragments(fragments);
mainViewPager.setAdapter(fixPagerAdapter);
//将ViewPager与TabLayout绑定
tabLayout.setupWithViewPager(mainViewPager);
//显示样式
tabLayout.setTabMode(TabLayout.MODE_FIXED);
}
fragment工程类的编写
public class FragmentFactory {
/**
* 推荐
*/
public static final int TAB_RECOMMEND=0;
/**
* 分类
*/
public static final int TAB_CATEGORY=1;
/**
* 排行
*/
public static final int TAB_TOP=2;
/**
* 管理
*/
public static final int TAB_APPMANAGER=3;
/**
* 我的
*/
public static final int TAB_MY=4;
private static Map<Integer,BaseFragment> mFragments=
new HashMap<Integer,BaseFragment>();
public static BaseFragment createFragment(int index){
BaseFragment fragment= mFragments.get(index);
//如果之前没有创建,创建新的Fragment
if(fragment==null){
switch (index){
case TAB_RECOMMEND:
fragment=new RecommendFragment();
break;
case TAB_CATEGORY:
fragment=new CategoryFragment();
break;
case TAB_TOP:
fragment=new TopFragment();
break;
case TAB_APPMANAGER:
fragment=new AppManagerFragment();
break;
case TAB_MY:
fragment=new MyFragment();
break;
//
}
//把创建的Fragment 存起来
mFragments.put(index,fragment);
}
return fragment;
}
}
样式的编写
<style name="CustomTabLayoutTextAppearance"
parent="TextAppearance.AppCompat.Widget.ActionBar.Title.Inverse">
<item name="android:textSize">15sp</item>
</style>