TabLayout 提供水平布局以显示 tabs。
使用
TabLayout 继承自 HorizontalScrollView。
xml 布局代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabBackground="@android:color/holo_blue_dark"
app:tabIndicatorColor="@android:color/white"
app:tabIndicatorHeight="10dp"
app:tabSelectedTextColor="@android:color/white"
app:tabMode="scrollable"
app:tabTextAppearance="@style/AppTheme.TabLayout.TextAppearance" />
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:isScrollContainer="true"/>
</LinearLayout>
res/values/styles.xml
<style name="AppTheme.TabLayout.TextAppearance" parent="TextAppearance.Design.Tab">
<item name="android:textSize">20sp</item>
<item name="android:textColor">#00FF00</item>
<item name="textAllCaps">false</item>
</style>
属性 | 作用 |
---|---|
tabBackground | 标签的背景色 |
tabContentStart | 标签从Y轴起始位置的设置的偏移量处开始移动 |
tabGravity | Tab的重心,填充和居中两种,分别为fill和center |
tabMode | Tab的模式,固定和滚动两种,分别为fixed和scrollable |
tabTextColor | 默认状态下Tab字体颜色 |
tabSelectedTextColor | 选中的字体颜色 |
tabIndicatorColor | 用于显示当前选定的标签的指示器的颜色。 |
tabIndicatorHeight | 指示器的高度 |
tabMaxWidth | 标签的最大宽度 |
tabMinWidth | 标签的最小宽度 |
tabPadding | 标签的填充距离 |
tabTextAppearance | 设置Text字体风格 |
tabPadding | 底部边距 |
tabPaddingEnd | 右边边距 |
tabPaddingStart | 左边距 |
tabPaddingTop | 顶部边距 |
java 代码
private void initTabLayout() {
final List<String> titles = new ArrayList<>();
for (int i = 0; i < 10; i++) {
titles.add("tab" + i);
}
final List<TabFragment> fragments = new ArrayList<>();
TabFragment tabFragment;
for (int i = 0; i < titles.size(); i++) {
mTabLayout.addTab(mTabLayout.newTab().setText(titles.get(i)));
tabFragment = new TabFragment();
Bundle bundle = new Bundle();
bundle.putString("tab_text", titles.get(i));
tabFragment.setArguments(bundle);
fragments.add(tabFragment);
}
FragmentPagerAdapter fragmentPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getCount() {
return fragments.size();
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return titles.get(position);
}
};
mViewPager.setAdapter(fragmentPagerAdapter);
mTabLayout.setupWithViewPager(mViewPager);
}
实现效果
![](https://img.haomeiwen.com/i6770217/f1448a1511c5a71c.gif)
网友评论