简体   繁体   中英

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.

So I tried to assign some random id, say 1001 to my programmatically created view -

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.

Is there any other way I can use my own generated views in TabHost, or a tabbed interface?

You need to use the version of the overloaded setContent() method that takes a TabHost.TabContentFactory .

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;
        }));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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