Next, I'm making an app and using tablayout on multiple screens. But in all cases this problem happens. When I use the swipe to select the fragment on the side, the fragment changes, but the selected tab remains the first one. The code:
public class RegrasTab extends AppCompatActivity implements TabLayout.OnTabSelectedListener{
private TabLayout tabLayout;
private ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_regras_tab);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.addTab(tabLayout.newTab().setText("Open 2.0"));
tabLayout.addTab(tabLayout.newTab().setText("TK2"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
viewPager = (ViewPager) findViewById(R.id.pager);
PagerRegras adapter = new PagerRegras(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
tabLayout.addOnTabSelectedListener(this);
}
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
PagerRegras.java:
public class PagerRegras extends FragmentStatePagerAdapter {
int tabCount;
public PagerRegras(FragmentManager fm, int tabCount) {
super(fm);
this.tabCount= tabCount;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
TabOpen open = new TabOpen();
return open;
case 1:
TabTK2 tk2 = new TabTK2();
return tk2;
default:
return null;
}
}
@Override
public int getCount() {
return tabCount;
}
The images: (notice that selecting the second tab via swipe, the first one is still selected)