Search code examples
androidandroid-fragmentsandroid-tabhost

Android - How can I pass myFragment.class as a parameter to a function


I'm creating a Tab Fragment with custom Tab controls as follows

View tabView = createTabView(getActivity(),"Tab 1");
mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator(tabView),
                Tab1Fragment.class, null);

But rather than have these two lines of code for every tab in the view I'd like to create a generic function eg

private void addTab(String sTag, String sTitle, Class<Fragment> cls) {
    View tabView = createTabView(getActivity(),sTitle);
    mTabHost.addTab(mTabHost.newTabSpec(sTag).setIndicator(tabView),
    cls, null);
}

The problem is I can't work out how to cast Tab1Fragment.class to pass it into the function


Solution

  • Generics in Java are not covariant, viz. you cannot pass in a subtype of Fragment to satisfy the generic parameter type of Fragment. This is the correct way to do what you want:

    private <T extends Fragment> void addTab(String sTag, String sTitle, Class<T> cls) {
        View tabView = createTabView(getActivity(),sTitle);
        mTabHost.addTab(mTabHost.newTabSpec(sTag).setIndicator(tabView),
                cls, null);
    }