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.
01.
// This simple class just extends the LinearLayout and adds a Tab widget with 2 listviews, each in its own tab.
02.
public
class
ScoreScreen
extends
LinearLayout {
03.
private
TabHost host;
04.
private
TabWidget widget;
05.
06.
public
ScoreScreenView(Context context,
final
Scoreboard scoreboard) {
07.
super
(context);
08.
09.
this
.setOrientation(VERTICAL);
10.
11.
// Set up the tab widget and put in onto the view
12.
TabSpec tab;
13.
14.
host =
new
TabHost(context);
15.
host.setLayoutParams(
new
LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
16.
17.
widget =
new
TabWidget(context);
18.
widget.setId(android.R.id.tabs);
19.
host.addView(widget,
new
LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
20.
21.
// the TabHost needs a frame layout for the views on the tab
22.
FrameLayout frame =
new
FrameLayout(context);
23.
frame.setId(android.R.id.tabcontent);
24.
host.addView(frame,
new
LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
25.
26.
host.setup();
// Magic function that initialises everything
27.
28.
// Start adding tabs
29.
tab = host.newTabSpec(
"High Scores"
).setIndicator(
"High Scores"
).setContent(
new
TabContentFactory() {
30.
@Override
31.
public
View createTabContent(String tag) {
32.
ListView lv =
new
ListView(context);
33.
34.
lv.setAdapter(
new
ScoreAdaptor(scoreboard.highScores));
35.
return
lv;
36.
}
37.
});
38.
host.addTab(tab);
39.
40.
tab = host.newTabSpec(
"Your Scores"
).setIndicator(
"Your Scores"
).setContent(
new
TabContentFactory() {
41.
@Override
42.
public
View createTabContent(String tag) {
43.
ListView lv =
new
ListView(context);
44.
45.
lv.setAdapter(
new
ScoreAdaptor(scoreboard.playerScores));
46.
return
lv;
47.
}
48.
});
49.
50.
host.addTab(tab);
51.
52.
// Add the tab to the layout
53.
this
.addView(host);
54.
55.
// Set the padding for the frame so the content doesn't cover the tabs
56.
int
tabHeight = host.getTabWidget().getChildAt(host.getTabWidget().getChildCount() -
1
).getLayoutParams().height;
57.
frame.setPadding(
0
, tabHeight,
0
,
0
);
58.
}
59.
}
Now I guess we can both go back to doing whatever we were doing...
Sources
Most of the setup magic cames from PocketMagic.
The code to set the proper non-hardcoded tab height came from StackOverflow.