I'm trying to get use to Android Honeycomb by creating a simple text editing application which utilizes the Action Bar and tabs. I am running into an annoying issue though. After a tab has been created and added to the Action Bar I would like to change the text displayed on the tab. I thought that using the following method, ActionBar.Tab.setText(CharSequence arg0) would do the trick, however, it doesn't seem to be changing the viewable text. What's weirder still is that if I were to call getText() it returns the text that I changed the tab to. Below is a snippet of code that I am using to change the tab text:
int currentTabIndex = ab.getSelectedNavigationIndex();
currentTabTitle = (String) ab.getTabAt(currentTabIndex).getText(); // just to check
ab.getTabAt(currentTabIndex).setText(fileName); // change tab text
currentTabTitle = (String) ab.getTabAt(currentTabIndex).getText(); // just to check
I really am at a loss and have searched everywhere. I would greatly appreciate any advice that anyone has. Thanks for your time.
This is kind of a silly issue and adding and removing tabs is a bad idea because if you're using fragments you will end up removing and re-adding your fragment with its tab. Using a custom view seems to work much better and as an added bonus offers you greater customization.
Here's how to make a tab with a custom view that looks and behaves identical to the default ones:
ActionBar bar = getActionBar();
TabListener tabListener = new TabListener() {
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
};
Tab tab1 = bar.newTab()
.setText("Info")
.setTabListener(tabListener)
.setCustomView(makeTabDummy("Info", android.R.drawable.ic_menu_info_details));
bar.addTab(tab1);
and here is the pixel perfect dummy view:
private TextView makeTabDummy(String text, int icon) {
TextView tv = new TextView(this);
tv.setText(text);
tv.setTextColor(0xffffffff);
tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
tv.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT));
tv.setCompoundDrawablesWithIntrinsicBounds(icon, 0, 0, 0);
tv.setGravity(Gravity.CENTER);
return tv;
}
From here we can change icons and text on the tab without any problems at all. Example:
TextView tv = (TextView) tab1.getCustomView();
tv.setText("change the text!");
tv.setCompoundDrawablesWithIntrinsicBounds(android.R.drawable.btn_star_big_on, 0, 0, 0);
... and everything works as it should
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With