1.一般Tablayout的使用是和viewpager一起,可以轻松实现标签页的切换;不用我们自己再去监听事件,大大提高了编码效率
使用步骤:
首先,compile’com.android.support:design:25.3.1’导入依赖
其次,在xml文件中使用如下代码
<android.support.design.widget.TabLayout
android:id=”@+id/tl_tab”
android:layout_width=”match_parent”
android:layout_height=”@dimen/csc_dp_48″
android:background=”@color/csc_white”
app:tabSelectedTextColor=”@color/csc_orange”// 选中标签的字体颜色
app:tabIndicatorColor=”@color/csc_orange”// 指示器的颜色
app:tabTextAppearance=”@style/TabLayoutTextStyle”// style下写一个style,内部属性来一个textsisze即可;
app:tabTextColor=”@color/csc_low_black”>
</android.support.design.widget.TabLayout
>
<android.support.v4.view.ViewPager
android:id=”@+id/vp_content”
android:layout_width=”match_parent”
android:layout_height=”match_parent”>
在Activity中写一个集合或者数组保存标签页面
public static finalString[]tabTitle=newString[]{“ss列表”,”xx列表”};
private TabAdapter tabAdapter;
存放fragment的集合;
在OnCreate()里面如下
@Override
protected voidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_goods_manager);
ButterKnife.bind(this);
tvCommonTitle.setText(“商品管理”);
List fragments =newArrayList<>();
for(inti =0; i
if(i ==0) {
fragments.add(GoodsFragment.newInstance(i +””));
}else{
fragments.add(ManagerFragment.newInstance(i +””));
}
}
tabAdapter=newTabAdapter(getSupportFragmentManager(), fragments);
//给ViewPager设置适配器
pager.setAdapter(tabAdapter);
//将TabLayout和ViewPager关联起来。
tab.setupWithViewPager(pager);
//通过反射设置指示器的宽度
setUpIndicatorWidth();
//设置可以滑动
tab.setTabMode(TabLayout.MODE_FIXED);
}
/**
*通过反射修改TabLayout Indicator的宽度(仅在Android 4.2及以上生效)
*/
private voidsetUpIndicatorWidth() {
try{
Class tabLayoutClass =tab.getClass();
Field tabStrip =null;
try{
tabStrip = tabLayoutClass.getDeclaredField(“mTabStrip”);
tabStrip.setAccessible(true);
}catch(NoSuchFieldException e) {
e.printStackTrace();
}
LinearLayout layout =null;
try{
if(tabStrip !=null) {
layout = (LinearLayout) tabStrip.get(tab);
}
for(inti =0; i < layout.getChildCount(); i++) {
View child = layout.getChildAt(i);
child.setPadding(0,0,0,0);
LinearLayout.LayoutParams params =newLinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT,1);
if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.JELLY_BEAN_MR1) {
params.setMarginStart(UiUtils.dp2px(this,40));
params.setMarginEnd(UiUtils.dp2px(this,40));
}
child.setLayoutParams(params);
child.invalidate();
}
}catch(IllegalAccessException e) {
e.printStackTrace();
}
}catch(Exception e) {
e.printStackTrace();
}
}
/**
* tablayout的适配器
*/
public classTabAdapterextendsFragmentPagerAdapter {
privateListfragments;
publicTabAdapter(FragmentManager fm, List fragments) {
super(fm);
this.fragments= fragments;
}
@Override
publicFragment getItem(intposition) {
returnfragments.get(position);
}
@Override
public intgetCount() {
returnfragments.size();
}
//设置tablayout标题
@Override
publicCharSequence getPageTitle(intposition) {
returntabTitle[position];
}
}
ok基本使用就是这样了,有错误的地方还望指正,谢谢