1

I have a TabListener in Android defined in this way:

public static class TabListener<T extends Fragment> 
    implements ActionBar.TabListener { ... }

An I have this source code:

Tab myTab = myActionBar.
                newTab().
                setText("Home").
                setTabListener(new TabListener<MyFragment>(
                    this, 
                    "Home", 
                    MyFragment.class
                ));
...

Now I want to put this into a method:

addTab("Home", ???);

private void addTab(String text, ???) {
    Tab myTab = myActionBar.
                newTab().
                setText(text).
                setTabListener(new TabListener<???>(
                    this, 
                    text, 
                    ???.class
                ));
    ...
}

What I have to fill in instead of ????

3 Answers 3

5

Your tab listener needs the type parameter to be a subclass of Fragment

public static class TabListener<T extends Fragment>

Therefore, you need to make sure it is the case in your code

addTab("Home", ???);

private <T extends Fragment> void addTab(String text, Class<T> clazz) {
    Tab myTab = myActionBar.
                newTab().
                setText(text).
                setTabListener(new TabListener<T>(
                    this, 
                    text, 
                    clazz
                ));
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

3
addTab("Home", MyFragment.class);

private void addTab(String text, Class<? extends Fragment> clazz) {
    Tab myTab = myActionBar.
            newTab().
            setText(text).
            setTabListener(new TabListener<>(
                this, 
                text, 
                clazz
            ));
    ...
}

2 Comments

Unfortunately, I use JRE6: '<>' operator is not allowed for source level below 1.7
that can be solved by introducing a factory method. but it's fine to have a <T> to addTab()
2

Something like this is probably what you're looking for:

private <T> void addTab(String text, Class<T> clazz) {
    Tab myTab = myActionBar.
            newTab().
            setText(text).
            setTabListener(new TabListener<T>(
                this, 
                text, 
                clazz
            ));
    ...
}

3 Comments

wildcard is better. and the class should be a subclass of Fragment
I get this error here new TabListener<T>: Bound mismatch: The type T is not a valid substitute for the bounded parameter <T extends Fragment> of the type MyActivity.TabListener<T>
This way, it works: private <T extends Fragment> void addTab(String text, Class<T> clazz)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.