ViewPager viewPager = findViewById(R.id.viewPager); viewPager.setAdapter(adapter); viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { // Called when the page is scrolled } @Override public void onPageSelected(int position) { // Called when a new page is selected } @Override public void onPageScrollStateChanged(int state) { // Called when the scroll state changes } });
ViewPager viewPager = findViewById(R.id.viewPager); viewPager.setAdapter(adapter); TabLayout tabLayout = findViewById(R.id.tabLayout); tabLayout.setupWithViewPager(viewPager); viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));This example demonstrates how to use the TabLayout and ViewPager together, and how to add a listener to the ViewPager that keeps the selected tab in sync with the current page. The code is located in the android.support.design.widget package library.