Tablelayout需要嵌套viewpager一起使用
布局文件
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:id="@+id/tas"
tabGravity="center"
tabIndicatorColor="@color/colorAccent"
tabMode="scrollable"
tabSelectedTextColor="@color/colorPrimaryDark"
tabTextColor="@color/colorPrimary"
>
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/vp"
android:layout_below="@+id/tas"
>
</android.support.v4.view.ViewPager>
Activity代码:
List<String> datas = new ArrayList<String>();
datas.add("Android");
datas.add("IOS");
datas.add("福利");
//适配器
vp.setAdapter(new FragmentPagerAdapter(getActivity().getSupportFragmentManager()) {
@Override
public Fragment getItem(int position) {
Fragment fragment=null;
//当选中的位置是对应的索引值的话 就加载那个Fragment
switch (position) {
case 0:
fragment=new AndroidFg();
break;
case 1:
fragment=new IosFg();
break;
case 2:
fragment=new FuliFg();
break;
default:
break;
}
return fragment;
}
@Override
public int getCount() {
return 3;
}
//设置tablelayout标题
public CharSequence getPageTitle(int position) {
return datas.get(position);
}
});
//进行关联
tas.setupWithViewPager(vp);
让下划线跟随文字长度而变化
/**
* 修改tabLayout下划线的宽度
*
* @param tabLayout
*/
public void reflex(final TabLayout tabLayout) {
tabLayout.post(new Runnable() {
@Override
public void run() {
try {
//拿到tabLayout的mTabStrip属性
LinearLayout mTabStrip = (LinearLayout) tabLayout.getChildAt(0);
int dp10 = dip2px(tabLayout.getContext(), 10);
for (int i = 0; i < mTabStrip.getChildCount(); i++) {
View tabView = mTabStrip.getChildAt(i);
//拿到tabView的mTextView属性 tab的字数不固定一定用反射取mTextView
Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");
mTextViewField.setAccessible(true);
TextView mTextView = (TextView) mTextViewField.get(tabView);
tabView.setPadding(0, 0, 0, 0);
//因为我想要的效果是 字多宽线就多宽,所以测量mTextView的宽度
int width = 0;
width = mTextView.getWidth();
if (width == 0) {
mTextView.measure(0, 0);
width = mTextView.getMeasuredWidth();
}
//设置tab左右间距为10dp 注意这里不能使用Padding 因为源码中线的宽度是根据 tabView的宽度来设置的
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
params.width = width;
params.leftMargin = dp10;
params.rightMargin = dp10;
tabView.setLayoutParams(params);
tabView.invalidate();
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
});
}
/**
* PX换DP
*
* @param context
* @param dpValue
* @return
*/
public int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
简书tablelayout的属性介绍
http://www.jianshu.com/p/2b2bb6be83a8