TabLayout介绍
TabLayout 是一个横向标签显示的布局,效果就是现在很多新闻客户端的那种顶部标签展示效果,并支持指示器、 ViewPager 联动
注意事项
Android最新版本 也就是AndoirdX是引用不到TabLayout的,必须加上
implementation ‘com.android.support:design:28.0.0’
这个依赖,同时要把build.gradle文件里
android {
compileSdkVersion 28
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "com.example.a2_27_tablayout"
minSdkVersion 24
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
所对应的SDK版本改成28,也就是如上代码28的位置,不然不会出来。
代码展示(案列)
需要三个Fragment。
acticity的代码
public class MainActivity extends AppCompatActivity {
private TabLayout tab;
private ViewPager vp;
private List<Fragment> list = new ArrayList<>();
private List<String > titles = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件
tab = (TabLayout) findViewById(R.id.tab);
vp = (ViewPager) findViewById(R.id.vp);
//添加数据
titles.add("标题1");
titles.add("标题2");
titles.add("标题3");
list.add(new FragmentOne());
list.add(new FragmentTwo());
list.add(new FragmentThree());
//创建设配器
MyAdapter myAdapter = new MyAdapter(getSupportFragmentManager(),list,titles);
//设置适配器
vp.setAdapter(myAdapter);
//绑定显示效果
tab.setupWithViewPager(vp);
}
}
xml文件的布局代码
<?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=".MainActivity"
android:orientation="vertical">
<com.google.android.material.tabs.TabLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="@+id/tab"
app:tabMode="fixed"
app:tabSelectedTextColor="@color/colorPrimary"
android:layout_weight="1">
</com.google.android.material.tabs.TabLayout>
<androidx.viewpager.widget.ViewPager
android:id="@+id/vp"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="9"></androidx.viewpager.widget.ViewPager>
### 适配器的代码
public class MyAdapter extends FragmentPagerAdapter {
private List<Fragment> lists;
private List<String> titles;
public MyAdapter(@NonNull FragmentManager fm, List<Fragment> lists, List<String> titles) {
super(fm);
this.lists = lists;
this.titles = titles;
}
@NonNull
@Override
public Fragment getItem(int position) {
return lists.get(position);
}
@Override
public int getCount() {
return lists.size();
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
//把标题跟fragment的数据绑定起来
return titles.get(position);
}
}
效果展示
TabLayout的几个常用属性值
app:tabBackground 标签布局的背景色
app:tabIndicatorColor 指示器的颜色
app:tabIndicatorHeight 指示器的高度(如果不需要指示器可以设置为0dp)
app:tabMode 显示模式:默认 fixed(固定),scrollable(可横向滚动)
app:tabPadding 标签内边距
app:tabSelectedTextColor 标签选中的文本颜色
app:tabTextAppearance 标签文本样式
app:tabTextColor 标签未选中的文本颜色