Search code examples
androidandroid-studioandroid-tablayout

How to make the selector under tabs to scroll to the selected tab?


tablayout with scroll

I want to scroll the selector(pink line) to the next tab(on-fillup). my fragments are scrolling but the selector is unable to scroll. can anyone help?

MainActivity.java

//Adding the tabs using addTab() method
    tabLayout.addTab(tabLayout.newTab().setText("On Reserved"));
    tabLayout.addTab(tabLayout.newTab().setText("On Fill-up"));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

activity_main.java

<!-- our tablayout to display tabs  -->
<android.support.design.widget.TabLayout
    android:id="@+id/tabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

<!-- View pager to swipe views -->
<android.support.v4.view.ViewPager
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"></android.support.v4.view.ViewPager>

Solution

  • you have to assign tablayout in viewpager like below code

    // listener for tablayout when you select tab for change view
    tabLayout.setOnTabSelectedListener(this);
     // assign tablayout in viewpager
     viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    

    this is override method when you tap on tab then viewpager is change

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        viewPager.setCurrentItem(tab.getPosition());
    }
    
    @Override
    public void onTabUnselected(TabLayout.Tab tab) {
    
    }
    
    @Override
    public void onTabReselected(TabLayout.Tab tab) {
    
    }