I am using android.support.design.widget.TabLayout.
It has two tabs,
If user selects second tab On particular condition I want user to redirect to first tab and disallow him to go to sencond tab until condition matches.
To achieve this I tried,
tabLayout.getTabAt(0).select();
but it does not reselect first tab
This is because that view is still not initialized properly, and you are trying to perform some action.
As a solution you just need to put one hadler before selecting perticular tab.
new Handler().postDelayed(
new Runnable(){
@Override
public void run() {
tabLayout.getTabAt(yourTabIndex).select();
}
}, 100);
This is how I solved it:
tabLayout.getTabAt(CurrentItem).getCustomView().setSelected(true);
This worked for me:
int tabIndex = 2;
tabLayout.setScrollPosition(tabIndex,0f,true);
viewPager.setCurrentItem(tabIndex);
This is my setup. works fine for me.
//declare your tabs to be add on
TabLayout tlDailyView;
private TabLayout.Tab tabAppointment, tabSlots;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_daily_view, container, false);
initializeMembers();
setupTabLayout();
return view;
}
private void setupTabLayout() {
tlDailyView.addTab(tabAppointment, 0, true);
tlDailyView.addTab(tabSlots, 1, true);
tlDailyView.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition()) {
case 0:
//open fragment at position 0 here
case 1:
//open fragment at position 1 here
break;
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void initializeMembers() {
tabSlots = tlDailyView.newTab();
tabAppointment = tlDailyView.newTab();
tabAppointment.setText(R.string.tab_appts).select();
tabSlots.setText(R.string.tab_slots);
}
don't forget to initialize your tab layout above.
You can select the tab in Fragment.onViewCreated()
.
tabLayout.getTabAt(index specific).select();
It's too late but it might help other developers.
If you go inside and see how tabLayout.getTabAt(tabIndex).select();
has been implemented inside. You'll come to know that, it sends your flow to
onTabReselected(tab: TabLayout.Tab?)
and your flow doesn't go to
onTabSelected(tab: TabLayout.Tab?)
if your current tab and tabIndex are same. So this is very important to consider.
Mihir's answer gave me an idea to try this. Seems like it works without the hardcoded timer, and also correctly updates the scroll for selected tab:
final TabLayout tabLayout = ...;
tabLayout.postOnAnimation(new Runnable() {
@Override
public void run() {
tabLayout.getTabAt(2).select();
}
});