简介
com.google.android.material.tabs.TabLayout 用于实现滑动选项卡的功能,底部带有滑动动画,可以添加图片,实现顶部的滑动选选项卡,或者底部的标签栏
使用方法
1 导入依赖
implementation 'com.android.support:design:25.1.1'
2 编写视图xml
<com.google.android.material.tabs.TabLayout
android:id="@+id/tl_bto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent">
<com.google.android.material.tabs.TabItem
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="首页" />
<com.google.android.material.tabs.TabItem
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="我的" />
</com.google.android.material.tabs.TabLayout>
这个是实现底部标签栏的功能
3 活动里绑定视图控件以及按钮点击事件
private TabLayout mTabLayout;
private void bindView(){
mTabLayout = findViewById(R.id.tl_bto);
}
private void initTabLayout() {
mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition()) {
case 0:
//第一个fragment
Log.e("msg","one");
break;
case 1:
//第二个fragment
Log.e("msg","two");
break;
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
4 在调用定义的方法
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bindView();
initView(savedInstanceState);
}
private void initView(Bundle bundle){
initTabLayout();
}
5 实现效果