1. First add dependencies:
implementation 'com.google.android.material:material:1.2.1'
2. Implementation code:
1. xml file:
<com.google.android.material.tabs.TabLayout
android:id="@+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
app:tabGravity="fill"
app:tabIndicatorColor="#397AFC"
app:tabIndicatorHeight="1dp"
app:tabIndicatorFullWidth="false"
app:tabSelectedTextColor="#397AFC"
app:tabTextColor="#E80D0D"
app:tabMaxWidth="0dp"
app:tabMode="scrollable"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#888888"/>
<androidx.viewpager.widget.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
1. app:tabIndicatorColor indicates the color of the line
2. app:tabIndicatorHeight indicates the height of the line
3. app:tabTextColor unselected font color
4. app:tabSelectedTextColor selected font color
5. app:tabMode="scrollable", scroll mode, you can slide to view when there are many tab labels
6. app:tabMode="fixed", fixed mode, you cannot slide when there are many tab labels.
7. app:tabIndicatorFullWidth="true", true: the width fills the width of the TabLayout, false: the width is consistent with the width of the TextView
2、MainActivity:
private TabLayout tabLayout;
private ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
tabLayout = findViewById(R.id.tabLayout);
viewPager = findViewById(R.id.viewPager);
private List<Fragment> frameLayoutList = new ArrayList<Fragment>();
frameLayoutList.add(new AllFragment());
frameLayoutList.add(new FruitFragment());
frameLayoutList.add(new MeatFragment());
List<String> tabLayoutList = new ArrayList<>();
tabLayoutList.add("全部");
tabLayoutList.add("水果区");
tabLayoutList.add("肉类分区");
MyAdapter adapter = new MyAdapter(getSupportFragmentManager(), frameLayoutList, tabLayoutList);
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
}
3. Implement the internal class MyAdapter to inherit FragmentPagerAdapter:
public class MyAdapter extends FragmentPagerAdapter {
private List<Fragment> fragmentList;
private List<String> tabList;
public MyAdapter(FragmentManager fm, List<Fragment> frameLayoutList, List<String> tabLayoutList) {
super(fm);
this.fragmentList = frameLayoutList;
this.tabList = tabLayoutList;
}
@Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
@Override
public int getCount() {
return fragmentList.size();
}
@Override
public CharSequence getPageTitle(int position) {
return tabList.get(position);
}
}
3. Effect drawing
1. When app:tabIndicatorFullWidth="false", the width of the underline is the same as the width of the TextView font:
2. app:tabIndicatorFullWidth="true", the width fills the width of TabLayout: