0

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

QuantumTiger
  • 970
  • 1
  • 10
  • 22
  • possible duplicate of [How to pass a type as a method parameter in Java](http://stackoverflow.com/questions/2240646/how-to-pass-a-type-as-a-method-parameter-in-java) – C0D3LIC1OU5 Nov 25 '14 at 19:24

1 Answers1

2

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);
}
Jeffrey Mixon
  • 12,846
  • 4
  • 32
  • 55