简体   繁体   English

Android:使用TabHost以编程方式创建View

[英]Android: Using TabHost with programmatically created View

I want to create tabs which will show certain views I create through code. 我想创建标签,显示我通过代码创建的某些视图。 Now I can pass a View to TabHost, but only by id. 现在我可以将View传递给TabHost,但只能通过id传递。

So I tried to assign some random id, say 1001 to my programmatically created view - 所以我试着给我的编程创建视图分配一些随机ID,比如说1001 -

TabHost th = getTabHost();
View v=getMyView(); v.setId(1001);
th.addTab(th.newTabSpec("tab1").setIndicator("Monthly").setContent(v.getId()));

I get a Forced Close when I run this with the message that there is no view number 1001. 当我运行此消息时,我得到一个强制关闭,没有视图号1001。

Is there any other way I can use my own generated views in TabHost, or a tabbed interface? 有没有其他方法可以在TabHost或标签界面中使用我自己生成的视图?

You need to use the version of the overloaded setContent() method that takes a TabHost.TabContentFactory . 您需要使用带有TabHost.TabContentFactory的重载setContent()方法的版本

th.addTab(th.newTabSpec("tab1")
    .setIndicator("Monthly")
    .setContent(new TabHost.TabContentFactory() {
        @Override
        public View createTabContent(String tag) {
            if (tag.equals("tab1")) {
                return getMyView();
            }
            return null;
        }));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM