TabLayout介绍:
TabLayout继承自HorizontalScrollView,用作页面切换指示器,因使用简便功能强大而广泛使用在App中。
TabLayout的使用:
1、使用TabLayout导入的依赖:
implementation 'com.android.support:design:28.0.0'
2、TabLayout的常用属性:
app:tabBackground 标签布局的背景色
app:tabIndicatorColor 指示器的颜色
app:tabIndicatorHeight 指示器的高度(如果不需要指示器可以设置为0dp)
app:tabMode 显示模式:默认 fixed(固定),scrollable(可横向滚动)
app:tabPadding 标签内边距
app:tabSelectedTextColor 标签选中的文本颜色
app:tabTextAppearance 标签文本样式
app:tabTextColor 标签未选中的文本颜色
3、Fragment+ViewPager+TabLayout的组合需要ViewPager和TabLayout在代码中进行绑定
绑定方法:
setupWithViewPager();
4、TabLayout的创建:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".WelcomActivity"
android:orientation="vertical">
<com.google.android.material.tabs.TabLayout
android:id="@+id/tl_id"
android:layout_width="match_parent"
android:layout_height="match_parent">
</com.google.android.material.tabs.TabLayout>
</LinearLayout>
5、Java代码:
private List<WelcomFragment> list;
private List<String> lists;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcom);
initView();//初始化
}
private void initView() {
//初始化控件
ViewPager viewPager = findViewById(R.id.vp_id);
TabLayout tabLayout = findViewById(R.id.tl_id);
//初始化ViewPager的数据源
list = new ArrayList<>();
for (int i = 0; i < 8; i++) {
WelcomFragment fragment = new WelcomFragment();
list.add(fragment);
}
//初始化TabLayout的数据源
lists = new ArrayList<>();
lists.add("首页");
lists.add("新闻");
lists.add("图片");
lists.add("美女");
lists.add("美女爱");
lists.add("美女1");
lists.add("美女2");
lists.add("美女3");
//将tabLayout和viewPager进行绑定
tabLayout.setupWithViewPager(viewPager);
//设置适配器
viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
@Override
public Fragment getItem(int position) {//返回当前选中的条目
return list.get(position);
}
@Override
public int getCount() {//返回数据源的长度
return list.size();
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {返回TagLayout当前选中的条目
return lists.get(position);
}
});
}