How to add programmatically generated gallery to tab layout?

霸气de小男生 提交于 2019-12-12 02:25:58

问题


I write a method to generate gallery at run time.

private Gallery createGallery(ImageAdapter imageAdapter) {

    Gallery sampleGallery = new Gallery(getApplicationContext());
    sampleGallery.setLayoutParams(new ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.FILL_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
    sampleGallery.setGravity(Gravity.FILL_VERTICAL);
    sampleGallery.setSpacing(5);
    sampleGallery.setAdapter(imageAdapter);
    sampleGallery.setSelection(1);
    return sampleGallery;

}

Then I create a galley and try to set it to a Tab Layout.

final TabHost mTabHost = (TabHost) findViewById(R.id.tabHost);
    mTabHost.setup();
    Gallery tabGallery = createGallery(brkingNewAdapter); // my image adapter
    tabGallery.setId(R.id.gallery_1);
    mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator("TAB 1")
            .setContent(R.id.gallery_1));

R.id.gallery_1 is defined as mentions in here.

I get a exception as follows.

Could not create tab content because could not find view with id 2130968576

Any help on this?

Thank you in advance.


回答1:


You should take a look at TabContentFactory.

The solution for you would be to implement TabContentFactory and return the Gallery instance in the createTabContent method and use setContent(TabHost.TabContentFactory contentFactory) method in addTab.

class GalleryContentFactory implements TabContentFactory{
    private ImageAdapter imageAdapter;
    public GalleryContentFactory(ImageAdapter imageAdapter){
        this.imageAdapter = imageAdapter;
    }
    public View createTabContent(String tag){
        Gallery sampleGallery = new Gallery(getApplicationContext());
        sampleGallery.setLayoutParams(new ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.FILL_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
        sampleGallery.setGravity(Gravity.FILL_VERTICAL);
        sampleGallery.setSpacing(5);
        sampleGallery.setAdapter(imageAdapter);
        sampleGallery.setSelection(1);
        return sampleGallery;
    }
}

and for adding to the tab:

GalleryContentFactory galleryFactory = new GalleryContentFactory(brkingNewAdapter);
mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator("TAB 2")
            .setContent(galleryFactory));


来源:https://stackoverflow.com/questions/10227115/how-to-add-programmatically-generated-gallery-to-tab-layout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!