TabLayout
简述
TabLayout是Android support中的一个控件android.support.design.widget.TabLayout,Google在升级了AndroidX之后,将TabLayout迁移到material包下面去了com.google.android.material.tabs.TabLayout,原来的support下面的TabLayout从API 29开始就不再维护了。所以如果项目已经升级了AndroidX,建议直接使用后者。TabLayout一般结合ViewPager+Fragment的使用实现滑动的标签选择器。
比如新闻标签切换
看下TabLayout的继承关系,如下图
support包下面的
material包下面的
TabLayout继承的HorizontalScrollView,所以支持左右滑动,下面写的简单的例子看看效果。
简单示例
activity_tab.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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">
<com.google.android.material.tabs.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:tabTextColor="@color/colorPrimary"
app:tabSelectedTextColor="@color/colorPrimaryDark"
/>
<androidx.viewpager.widget.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@+id/tab_layout"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
ConstraintLayout 布局里面就一个TabLayout和一个ViewPager,tabSelectedTextColor和tabTextColor属性分别设置标签选中和未选中状态的文字颜色,其他属性后面介绍。
TabFragment.java
public class TabFragment extends Fragment {
public static TabFragment newInstance(String label) {
Bundle args = new Bundle();
args.putString("label", label);
TabFragment fragment = new TabFragment();
fragment.setArguments(args);
return fragment;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_tab, container, false);
}
@Override
public void onStart() {
super.onStart();
String label = getArguments().getString("label");
TextView text = getView().findViewById(R.id.tv_bg);
text.setText(label);
text.setBackgroundColor(Color.rgb((int)(Math.random() * 255)