current position:Home>Introduction to TabLayout (com.google.android.material.tabs.TabLayout)

Introduction to TabLayout (com.google.android.material.tabs.TabLayout)

2023-01-25 11:31:23Someone from Yungu Li

TabLayout的使用

一、Import of control library

TabLayout是Android support中的一个控件android.support.design.widget.TabLayout,Google在升级了AndroidX之后,将TabLayout迁移到material包下面去了com.google.android.material.tabs.TabLayout,原来的support下面的TabLayout从API 29开始就不再维护了.所以如果项目已经升级了AndroidX,建议直接使用后者.这里开始使用Androidx了,引入如下:

 implementation 'com.google.android.material:material:1.2.0-alpha06'

二、基本使用

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tab" />

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tab"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:tabMode="scrollable" />
    
</androidx.constraintlayout.widget.ConstraintLayout>

The main page layout is oneViewPager和TabLayout

TabFragment.java

public class TabFragment extends Fragment {
    

    public TabFragment(String str) {
    
        Bundle b = new Bundle();
        b.putString("key", str);
        setArguments(b);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    
        View view = inflater.inflate(R.layout.fragment_tab, container, false);
        TextView textView = view.findViewById(R.id.text);
        textView.setText(getArguments().getString("key"));
        textView.setBackgroundColor(Color.rgb((int) (Math.random() * 255), (int) (Math.random() * 255), (int) (Math.random() * 255)));
        return view;
    }

}

TabFragment中就一个TextView,每一个fragment设置不同的label和背景颜色.

MainActivity.java

public class MainActivity extends AppCompatActivity {
    
    private ArrayList<Fragment> fragments = new ArrayList<>();
    private String[] titles = new String[]{
    "欧冠", "英超", "西甲", "意甲", "德甲", "法甲", "中超", "欧联杯", "皇马", "巴萨", "拜仁", "利物浦"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    private void init() {
    
        TabLayout tabLayout = findViewById(R.id.tab);
        ViewPager viewPager = findViewById(R.id.viewpager);

        for (int i = 0; i < titles.length; i++) {
    
            fragments.add(new TabFragment(titles[i]));
        }

        FmPagerAdapter pagerAdapter = new FmPagerAdapter(Arrays.asList(titles), fragments, getSupportFragmentManager());
        viewPager.setAdapter(pagerAdapter);

        tabLayout.setupWithViewPager(viewPager);
    }

}

简单的分3步:

  • 找到TabLayout
  • 给ViewPager设置adapter
  • 设置TabLayout和ViewPagerlinkage between

运行结果:
在这里插入图片描述

  • 注意:就是在给ViewPager设置Adapter的时候,一定要重写getPageTitle(int position)方法
  • 三、TabLayout属性介绍

tabIndicatorFullWidth

Set the width of the indicator line to match the width of the text,那么就可以设置tabIndicatorFullWidth属性为false,默认为true
在这里插入图片描述

tabRippleColor

点击每一个tab的时候,会出现渐变的背景色
设置 app:tabRippleColor=“@color/green”
在这里插入图片描述
如果想要去掉这个点击时的背景,可以通过设置tabRippleColorThe property value is a transparent background color

tabTextAppearance

TabLayout并没有直接设置字体大小样式的属性,这时候就可以通过设置自定义属性tabTextAppearance来实现 app:tabTextAppearance=“@style/TextStyle”

    <style name="TextStyle">
        <item name="android:textSize">20sp</item>
        <item name="android:textStyle">bold</item>
    </style>

tabIndicatorHeight

这个属性设置指示器的高度,如果我们不需要显示指示器,则可以通过设置tabIndicatorHeight等于0来实现

tabIndicatorGravity

这个属性可以设置指示器的显示位置,可选值有bottom(默认)、center、top、stretch

stretch

在这里插入图片描述

app:tabBackground

改变整个TabLayout的颜色,直接在xml中设置:app:tabBackground=“@color/blue”.

app:tabContentStart

TabLayoutThe offset at which the text content in ,自由scrollable时候有效

在这里插入图片描述
The system default font starts with 16dp,The second row of labels is Settingsapp:tabContentStart="16dp"以后的情况

tabPaddingStart和tabPaddingEnd

当tabmode 是fix时候,解决tabThe font becomes smaller when the font is squeezed
在这里插入图片描述
Set the following two lines of code,问题就解决了:亲测有效;

        app:tabPaddingEnd="0dp"
        app:tabPaddingStart="0dp"

在这里插入图片描述

You can realize the message red dot by defining the layout yourself

在这里插入图片描述

自定义layout的item_red_dot.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name"
        android:textAppearance="@style/tab_normal_style"
        android:textSize="17sp" />

    <View
        android:layout_width="8dp"
        android:layout_height="8dp"
        android:layout_gravity="end|top"
        android:background="@color/colorAccent" />
</FrameLayout>

java代码

public class RedDotActivity extends AppCompatActivity {
    

    private ArrayList<Fragment> fragments = new ArrayList<>();

    private String[] titles = new String[]{
    "欧冠", "英超", "西甲", "意甲", "德甲", "法甲", "中超", "欧联杯", "皇马", "巴萨", "拜仁", "利物浦"};


    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    private void init() {
    
        TabLayout tabLayout = findViewById(R.id.tab);
        ViewPager viewPager = findViewById(R.id.viewpager);

        for (int i = 0; i < titles.length; i++) {
    
            tabLayout.addTab(tabLayout.newTab().setCustomView(R.layout.item_red_dot));
            fragments.add(new TabFragment(titles[i]));
        }

        for (int i = 0; i < titles.length; i++) {
    
            TextView view = tabLayout.getTabAt(i).getCustomView().findViewById(R.id.text1);
            view.setText(titles[i]);
        }

        FmPagerAdapter pagerAdapter = new FmPagerAdapter(Arrays.asList(titles), fragments, getSupportFragmentManager());
        viewPager.setAdapter(pagerAdapter);

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
    
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
    
                View customView = tab.getCustomView();
                if (customView == null) {
    
                    tab.setCustomView(R.layout.item_red_dot);
                }
                TextView textView = tab.getCustomView().findViewById(R.id.text1);
                textView.setTextAppearance(RedDotActivity.this, R.style.tab_select_style);
                viewPager.setCurrentItem(tab.getPosition(),true);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
    
                View customView = tab.getCustomView();
                if (customView == null) {
    
                    tab.setCustomView(R.layout.item_red_dot);
                }
                TextView textView = tab.getCustomView().findViewById(R.id.text1);
                textView.setTextAppearance(RedDotActivity.this, R.style.tab_normal_style);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
    

            }
        });

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
    
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    
                tabLayout.setScrollPosition(position, positionOffset, true, true);
            }

            @Override
            public void onPageSelected(int position) {
    
                tabLayout.getTabAt(position).select();
            }

            @Override
            public void onPageScrollStateChanged(int state) {
    

            }
        });

    }

}

style内容

    <style name="tab_normal_style">
        <item name="android:textSize">15sp</item>
        <item name="android:textStyle">normal</item>
        <item name="android:textColor">@color/black</item>
    </style>

    <style name="tab_select_style">
        <item name="android:textSize">17sp</item>
        <item name="android:textStyle">bold</item>
        <item name="android:textColor">@color/green</item>
    </style>

copyright notice
author[Someone from Yungu Li],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2023/025/202301251120395334.html

Random recommended