理解Activity的setContentView

发布于 2024-09-08 14:53:47 字数 913 浏览 0 评论 0原文

我需要“按需”以编程方式创建所有 UI,这意味着我无法使用任何 XML。这是我所做的伪代码:

View v = new MyView();
activity.setContentView(v);

tabHost = new TabHost();
....
tabHost.setup();
TabSpec tabSpec = _tabHost.newTabSpec(page);
        tabSpec.setIndicator(title);
        tabSpec.setContent((TabContentFactory) this);

activity.setContentView(tabHost);

因此,当调用 TabContentFactory 时,我返回当前活动的内容视图。基本上我所做的就是获取当前视图并将其包装在 tabhost 中。 它工作了一半,当我这样做时,我可以看到选项卡栏,但只有其下方的黑色视图,如果我单击其他选项卡,然后单击返回,那么我可以看到视图,一切都按预期工作。
现在为什么我认为它与 setContentView 有关,因为当我这样做时:

   View v = new MyView();
//    activity.setContentView(v); // we don't use it as current content view


tabHost = new TabHost();
....
tabHost.setup();
TabSpec tabSpec = _tabHost.newTabSpec(page);
        tabSpec.setIndicator(title);
        tabSpec.setContent((TabContentFactory) this);

然后一切都工作正常。 任何帮助表示感谢,谢谢!

I need to create all the UI programmatically "on demand", this means I can't use any XML. This is the pseudo code of what I do:

View v = new MyView();
activity.setContentView(v);

tabHost = new TabHost();
....
tabHost.setup();
TabSpec tabSpec = _tabHost.newTabSpec(page);
        tabSpec.setIndicator(title);
        tabSpec.setContent((TabContentFactory) this);

activity.setContentView(tabHost);

so when TabContentFactory is called I return the view which is the content view of the current activity. Basically what I do is taking current view and wrapping it in the tabhost.
It half works, when I do this I'm able to see the tabbar, but only black view below it, if I click on other tab and then click back then I can see the view, everything works as intended.
Now why I think it's related to setContentView, because when I do this:

   View v = new MyView();
//    activity.setContentView(v); // we don't use it as current content view


tabHost = new TabHost();
....
tabHost.setup();
TabSpec tabSpec = _tabHost.newTabSpec(page);
        tabSpec.setIndicator(title);
        tabSpec.setContent((TabContentFactory) this);

Then everything is working perfectly.
Any help appreciated, thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夜深人未静 2024-09-15 14:53:47

回答我自己的问题,我发现出了什么问题,当调用 setContentView 时,视图会附加到父级,这就是它没有出现在 tabhost 中的原因。要从其父视图中删除视图,可以使用以下代码:

ViewGroup vg = (ViewGroup)(myView.getParent());
vg.removeView(myView);

Answering my own question, I found what was wrong, when setContentView is called then the view attaches to the parent and that's why it does not appear in the tabhost. To remove the view from it's parent this code can be used:

ViewGroup vg = (ViewGroup)(myView.getParent());
vg.removeView(myView);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文