user1410081
user1410081

Reputation:

Android tablayout selecting the last tab instead of first

I need your help. I have a tablayout with tintable imageview and textview. I want to highlight the default selected tab which is the first one. This is my sample code:

TabLayout.Tab tab;
mTabs = (TabLayout) findViewById(R.id.tabs);
mViewpager = (ViewPager) findViewById(R.id.viewpager);
MyPagerAdapter pagerAdapter = new MyPagerAdapter(getSupportFragmentManager());

mViewpager.setAdapter(pagerAdapter);
mViewpager.addOnPageChangeListener(new MyPageScrollListener(mTabs));
mTabs.setupWithViewPager(mViewpager);

// Iterate over all tabs and set the custom view
for (int i = 0; i < mTabs.getTabCount(); i++) {
    tab = mTabs.getTabAt(i);
    tab.setCustomView(pagerAdapter.getTabView(i));
}

mTabs.setOnTabSelectedListener(new MyOnTabSelectedListener());   
tab.select();

But it's selecting the last tab. Anyone here knows how to fix this? I'd appreciate any kind of help. Thanks!

Upvotes: 0

Views: 5526

Answers (3)

Chris8447
Chris8447

Reputation: 306

I found a better solution. Instead if selecting the tab from the TabLayout you can do this with the ViewPager like so:

ViewPager viewPager = (ViewPager) findViewById(R.id.restaurant_menu_viewPager);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);

// ViewPager mit TabLayout verknüpfen
TabLayout tabLayout = (TabLayout) findViewById(R.id.restaurant_menu_tabLayout);
tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(1);

See the post here: https://stackoverflow.com/a/38762670/7318519

Upvotes: 1

user1410081
user1410081

Reputation:

Finally, I found a solution here: link

I added:

mTabs.getTabAt(1).select();    
mTabs.getTabAt(0).select();

And it works!

Upvotes: 1

StefMa
StefMa

Reputation: 3434

You selected the last tab. Take a look at your source code :)

TabLayout.Tab tab;
...
for (int i = 0; i < mTabs.getTabCount(); i++) {
    tab = mTabs.getTabAt(i);
}
...
tab.select();

tab is the last tab you will get with getTabAt(int position).

So when you want to select the first tab this will help

maTabs.getTabAt(0).select();

Another (maybe better) solution is to turn the for loop into this

for (int i = mTabs.getTabCount() - 1; i >= 0; i--) {
        tab = mTabs.getTabAt(i);
}

Then your "last" tab you are getting in this loop is the first tab in your TabLayout.

An working full example code looks like this gist.

Upvotes: 0

Related Questions