protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TabHost tabHost = new TabHost(this);
tabHost.setId(2);
TabWidget tabWidget = new TabWidget(this);
tabWidget.setId(android.R.id.tabs);
tabHost.addView(tabWidget, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
FrameLayout tabcontentFrame = new FrameLayout(this);
tabcontentFrame.setId(android.R.id.tabcontent);
tabHost.addView(tabcontentFrame, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
tabHost.setup();
LinearLayout lay = new LinearLayout(this);
lay.setId(1);
...
TabSpec spec = tabHost.newTabSpec(" ");
spec.setContent(lay.getId());
spec.setIndicator(" ");
tabHost.addTab(spec);
//mGame.addView(lay);
setContentView(tabHost);
}
我想向 TabSpec
添加一个 View (LinearLayout),但我在行中遇到了错误:
spec.setContent(lay.getId());
错误:无法创建标签内容,因为找不到 ID 为 1 的 View
。
我不想使用任何 xml。添加到 TabSpec
///编辑
其实我发现了一个问题。 LinearLayout lay
应该首先添加到 tabcontentFrame
,但它仍然无法正常工作,我得到下一个 RunTimeException
,原因是 Resources$ NotFoundException
消息 无法启动 Activity ComponentInfo{com.example.konsolatrx/konsolatrx.TrxConsole}:android.content.res.Resources$NotFoundException:资源 ID #0x0
错误在行 tabHost.addTab(spec);
///解决方案
好的,我找到了答案。
问题在于:
TabHost tabHost = new TabHost(this);
应该是:
TabHost tabHost = new TabHost(this, null);
必须指定属性集,但我不知道为什么。也许有人可以解释。 NKN 代码很好,但不是这个问题的解决方案,只是实现我想要的其他方式。
最佳答案
我用的是这样的:
// Being th the TabHost
final TabSpec setContent = th.newTabSpec(tag).setIndicator(tabview).setContent(new TabContentFactory() {
public View createTabContent(String tag) {
final View ll_view = LayoutInflater.from(globvars.getContext()).inflate(R.layout.tabs_content, null);
final TextView view = (TextView) ll_view.findViewById(R.id.tabsContent);
// do all the stuff you need to do to your view
return ll_view;
}
});
th.addTab(setContent);
关于android - 如何将 View 设置为 TabSpec 的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21427188/