preface

Recently in writing the design project, the project needs to use the TabLayout+ViewPager way to achieve the requirements, but the two controls are not very familiar with, so SPECIALLY write a BOLG record. ViewPager2 was introduced at Google I/O 2019 to replace ViewPager and includes several new features and enhanced UI and code experiences. ViewPager is no longer maintained. TabLayout is often used in conjunction with ViewPager.

Demo

  1. build.gradleIn theThe introduction of resources
// Import material UI implementation directly"Com. Google. Android. Material: material: 1.1.0." "
Copy the code
  1. Layout file writing
<! -- activity_main.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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        app:tabGravity="center"
        app:tabIndicatorColor="#ff678f"
        app:tabIndicatorFullWidth="false"
        app:tabIndicatorHeight="2dp"
        app:tabMode="scrollable"
        app:tabSelectedTextColor="#ff678f"
        app:tabTextColor="# 333333"
        app:tabUnboundedRipple="true" />

    <! TabIndicatorFullWidth is set to false to match the width of the text tabUnboundedRipple TabGravity can be set to Center or Fill; "Center" means "center", "fill" means "full screen". TabMode can set fixed and scrollable; Fixed: refers to the fixed TAB; Scrollable means that a TAB can slide. TabTextColor TAB text color tabSelectedTextColor TAB color when selected -->

    <! ViewPager2 internal RecyclerView so need to set the orientation of the page change direction -->
    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal" />
</LinearLayout>
Copy the code
  1. The code
public class MainActivity extends AppCompatActivity {

    private TabLayout tabLayout;
    private ViewPager2 viewPager2;

    private int activeColor = Color.parseColor("#ff678f");
    private int normalColor = Color.parseColor("# 666666");

    private int activeSize = 20;
    private int normalSize = 14;

    private ArrayList<Fragment> fragments;
    private TabLayoutMediator mediator;

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

        tabLayout = findViewById(R.id.tab_layout);
        viewPager2 = findViewById(R.id.view_pager);

        final String[] tabs = new String[]{"Attention"."Recommended"."New"};

        // Disable preloading
        viewPager2.setOffscreenPageLimit(ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT);
        //Adapter
        viewPager2.setAdapter(new FragmentStateAdapter(getSupportFragmentManager(), getLifecycle()) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                //FragmentStateAdapter internally manages instantiated Fragment objects.
                // There is no need to worry about reuse
                return TestFragment.newInstance(tabs[position]);
            }

            @Override
            public int getItemCount(a) {
                returntabs.length; }});//viewPager page switch listener
        viewPager2.registerOnPageChangeCallback(changeCallback);

        mediator = new TabLayoutMediator(tabLayout, viewPager2, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                // You can customize the TabView here
                TextView tabView = new TextView(MainActivity.this);

                int[][] states = new int[2] []; states[0] = new int[]{android.R.attr.state_selected};
                states[1] = new int[] {};int[] colors = new int[]{activeColor, normalColor};
                ColorStateList colorStateList = newColorStateList(states, colors); tabView.setText(tabs[position]); tabView.setTextSize(normalSize); tabView.setTextColor(colorStateList); tab.setCustomView(tabView); }});// Execute this sentence to bind the two
        mediator.attach();
    }

    private ViewPager2.OnPageChangeCallback changeCallback = new ViewPager2.OnPageChangeCallback() {
        @Override
        public void onPageSelected(int position) {
            // You can set the TAB size when selected
            int tabCount = tabLayout.getTabCount();
            for (int i = 0; i < tabCount; i++) {
                TabLayout.Tab tab = tabLayout.getTabAt(i);
                TextView tabView = (TextView) tab.getCustomView();
                if (tab.getPosition() == position) {
                    tabView.setTextSize(activeSize);
                    tabView.setTypeface(Typeface.DEFAULT_BOLD);
                } else{ tabView.setTextSize(normalSize); tabView.setTypeface(Typeface.DEFAULT); }}}};@Override
    protected void onDestroy(a) {
        mediator.detach();
        viewPager2.unregisterOnPageChangeCallback(changeCallback);
        super.onDestroy(); }}Copy the code

rendering

The Demo link

Refer to the article

  • ViewPager2 major update to support offscreenPageLimit
  • Android ViewPager2 & TabLayout
  • ViewPager2 and TabLayout
  • TabLayout app:tabMode and APP: tabGravity