以往我們想要實現這樣的效果,要麼去找三方開源庫,要麼自己動手寫viewpager,然後根據viewpager的滑動計算指示器的滑動距離來實現。現在在google提供的design包裏有一個tablayout可以幫助我們快速實現。
<android.support.design.widget.TabLayout
android:id="@+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/mainColor"
app:tabIndicatorColor="@color/white"
app:tabSelectedTextColor="@color/white"
app:tabTextColor="@color/white"
>
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:layout_below="@+id/tablayout"
android:id="@+id/vp"
android:layout_width="match_parent"
android:layout_height="match_parent"></android.support.v4.view.ViewPager>
來看佈局文件,首先是tablayout,然後在下面寫一個viewpager控件。tablayout中app:tabIndicatorColor表示指示器顏色,app:tabSelectedTextColor表示被選擇時候文字顏色,app:tabTextColor表示默認顏色。
tabLayout = (TabLayout) view.findViewById(R.id.tablayout);
vp = (ViewPager) view.findViewById(R.id.vp);
fragmentList = new ArrayList<>();
fragmentList.add(new Fragment1());
fragmentList.add(new Fragment2());
fragmentList.add(new Fragment3());
fragmentList.add(new Fragment4());
adapter = new MyAdapter (getActivity().getSupportFragmentManager(),fragmentList);
vp.setAdapter(adapter);
tabLayout.setupWithViewPager(vp);
通過tablayout的setupWidthViewPager就可以把tablayout和viewpager關聯起來。
再來看看adapter:
public class MyAdapter extends FragmentPagerAdapter {
private List<Fragment> list_fragment; //fragment列表
private String[] list_Title = new String[]{"標題1","標題2","標題3","標題4"};
public MyAdapter (android.support.v4.app.FragmentManager fm, List<Fragment> list_fragment) {
super(fm);
this.list_fragment = list_fragment;
}
@Override
public Fragment getItem(int position) {
return list_fragment.get(position);
}
@Override
public int getCount() {
return list_fragment.size();
}
@Override
public CharSequence getPageTitle(int position) {
return list_Title[position];
}
}
getpageTitle方法裏返回各個position要知道的標題就可以在tablayout中正常顯示title了。
這樣就完成了簡單的tablayout的使用。
如果使用的時候發現滑動時文字有閃爍現象,可以把desigin包升級下就沒有問題了。