I am trying to find way to be able to fire an onclick event on a tab when this tab is the current tab.
I did try this way (among several other) with no success thou
The problem here is that setOnTabChangedListener
does not fire when clicking on the selected tab, and if you set an OnClickListener
on the tab, you lose the normal tab behavior.
So an easy solution is to put OnClickListener
on the tab, and inside it, set programatically that this is the current tab.
With TabHost
:
getTabWidget().getChildAt(0).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// custom code
tabHost.setCurrentTab(0);
}
});
With TabLayout
tabLayout.getTabAt(0)setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// custom code
TabLayout.Tab tab = tabLayout.getTabAt(0);
tab.select();
}
}
});
Ugly fix:IN the onClickListener put :
tabHost.SetCurrentTab(OtherTab);
tabHost.SetCurrentTab(CurrentTab);
Where for index of Other Tab I use my simplest view under the tabs.
P.S. Customers always want their apps to be different :)
This is the code that I use (I have only 2 tabs Tab1 and Tab2):
getTabWidget().getChildAt(1).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG,"1"+getTabHost().getCurrentTabTag());
if (getTabHost().getCurrentTabTag().equals("Tab2")) {
Log.d(TAG,"2");
tabHost.setCurrentTab(0);
tabHost.setCurrentTab(1);
} else {
tabHost.setCurrentTab(1);
}
}
});
After gothrough many solutions for tab listener, I have found very simple solution...
getTabHost().setOnTabChangedListener(new OnTabChangeListener() {
@Override
public void onTabChanged(String tabId) {
int i = getTabHost().getCurrentTab();
Log.i("@@@@@@@@ ANN CLICK TAB NUMBER", "------" + i);
if (i == 0) {
Log.i("@@@@@@@@@@ Inside onClick tab 0", "onClick tab");
}
else if (i ==1) {
Log.i("@@@@@@@@@@ Inside onClick tab 1", "onClick tab");
}
}
});
If you want to try android.support.design.widget.TabLayout, you can achieve it like this:
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override public void onTabSelected(Tab tab) {
}
@Override public void onTabUnselected(Tab tab) {
}
@Override public void onTabReselected(Tab tab) {
}
});
If you have a custom tab layout, you might need to add this in your custom view, it solved my problem:
android:duplicateParentState="true"
This is working for me...
TabHost host = (TabHost)findViewById(R.id.tabHost);
host.setOnTabChangedListener(new OnTabChangeListener() {
@Override
public void onTabChanged(String tabId) {
int i = host.getCurrentTab();
if (i == 0) {
// your method 1
}
else if (i ==1) {
// your method 2
}
}
});