Android: Use tabs in your view without XML layout files and TabActivity class

The Android framework has been pretty good to work with so far, until I tried to add a tab widget onto my view. Bloody hell that was fussy!

I'm not particularly fond of using the WYSIWYG editor for the user interface,

All these weird errors were thrown around were due to some expectations within the TabHost and TabWidget classes.

I'll try to explain what I can remember.

// This simple class just extends the LinearLayout and adds a Tab widget with 2 listviews, each in its own tab.
public class ScoreScreen extends LinearLayout {
private TabHost host;
private TabWidget widget;

public ScoreScreenView(Context context, final Scoreboard scoreboard) {
super(context);

this.setOrientation(VERTICAL);

// Set up the tab widget and put in onto the view
TabSpec tab;

host = new TabHost(context);
host.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

widget = new TabWidget(context);
widget.setId(android.R.id.tabs);
host.addView(widget, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

// the TabHost needs a frame layout for the views on the tab
FrameLayout frame = new FrameLayout(context);
frame.setId(android.R.id.tabcontent);
host.addView(frame, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

host.setup(); // Magic function that initialises everything

// Start adding tabs
tab = host.newTabSpec("High Scores").setIndicator("High Scores").setContent(new TabContentFactory() {
@Override
public View createTabContent(String tag) {
ListView lv = new ListView(context);

lv.setAdapter(new ScoreAdaptor(scoreboard.highScores));
return lv;
}
});
host.addTab(tab);

tab = host.newTabSpec("Your Scores").setIndicator("Your Scores").setContent(new TabContentFactory() {
@Override
public View createTabContent(String tag) {
ListView lv = new ListView(context);

lv.setAdapter(new ScoreAdaptor(scoreboard.playerScores));
return lv;
}
});

host.addTab(tab);

// Add the tab to the layout
this.addView(host);

// Set the padding for the frame so the content doesn't cover the tabs
int tabHeight = host.getTabWidget().getChildAt(host.getTabWidget().getChildCount() -1).getLayoutParams().height;
frame.setPadding(0, tabHeight, 0, 0);
}
}

Now I guess we can both go back to doing whatever we were doing...

americapantsp1

Sources

Most of the setup magic cames from PocketMagic.

The code to set the proper non-hardcoded tab height came from StackOverflow.

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog