android - 如何将 View 设置为 TabSpec 的内容?

标签 android android-tabhost

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

时如何使此 View 可见

///编辑

其实我发现了一个问题。 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/

相关文章:

android - TabHost 中的 Webview = 以黑屏启动

java - 自定义适配器出现此错误 RecyclerView 未连接适配器;跳过布局

java - 将所有常量放在一个类android中

java - 防止后台Activity被杀死?

android - 以编程方式向 Activity 添加 View

android - 如何在选项卡中创建选项卡

java - 使用动态创建的 fragment 将选项卡添加到嵌套的 FragmentTabHost

android - 我的 onNewIntent 没有调用

android - 出现错误说 - "Entry name ' res/layout/test_toolbar.xml' 在创建签名 apk 时发生冲突

android - 在嵌套的 FragmentTabHost 中切换选项卡后 fragment 不可见