Show the selector in the indicated tab when I pulse onBackPressed in a TabLayout?

2

I have a TabLayout with 2 tabs , when I press above each tab the selector is shown above the indicated tab, but when I press the physical button on the back the selector remains in the previous tab.

TabLayout mTabLayout = (TabLayout) findViewById(R.id.tabs);
        mTabLayout.addTab(mTabLayout.newTab()); 
        mTabLayout.addTab(mTabLayout.newTab());


    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        switch (tab.getPosition()) {
            case 0:
                HomeFragment homeFragment = new HomeFragment();
                changeFragment(homeFragment, 0);
                break;
            case 1:
                EventsFragment eventsFragment = new EventsFragment();
                changeFragment(eventsFragment, 1);
                break;
        }
    }

    @Override
    public void onBackPressed() {
         if(mFragmentManager.getBackStackEntryCount() > 1){
            mFragmentManager.popBackStackImmediate();

        //Como hago que el selector naranja de la tab se muestre en la tab indicada

         }
    }

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerHorizontal="true"
    android:layout_above="@+id/tabs"
    android:id="@+id/fragment">

</FrameLayout>

<android.support.design.widget.TabLayout
    android:id="@+id/tabs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabMode="fixed"
    app:tabPaddingStart="-1dp"
    app:tabPaddingEnd="-1dp"
    app:tabGravity="fill"
    android:windowSoftInputMode="adjustPan"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:background="#000000" />

    
asked by Eric Retamero 15.03.2017 в 20:21
source

1 answer

1

You have to first save the index of the selected tab, as an example the variable CURRENT_TAB .

You can select the tab programmatically, for example if you want to select the second element (index 1) it would be done in this way taking the instance of the layout:

 @Override
 public void onBackPressed() {
   tabLayout.getTabAt(CURRENT_TAB).select();
 }

The other way is through the adapter to select the tab you want:

ViewPagerAdapter pagerAdapter = new ViewPagerAdapter(getChildFragmentManager());
viewPager.setAdapter(pagerAdapter);
viewPager.setCurrentItem(CURRENT_TAB);
    
answered by 15.03.2017 в 21:17