Question

I have two Fragment hierarchy:

Fragment -> MyAbstractFragment1 -> MyAbstractFragment2 -> ... -> MyAbstractFragmentN -> MyFragment

Fragment -> ListFragment -> MyAbstractListFragment1 -> MyAbstractListFragment2 -> ... -> MyAbstractListFragmentN -> MyListFragment

Both MyAbstractFragmentN and MyAbstractListFragmentN implements IMyFragment, so both MyFragment and MyListFragment implemets this interface too.

Is there any way to create field typed by Fragment which implements IMyFragment? So both 'MyListFragment' and 'MyFragment' would be correct type for it?

I can't create super class from both MyFragment and MyListFragment would inherit, because there are very different from the beginning. They have only Fragment in common, and IMyFragment from MyAbstractListFragmentN and MyAbstractFragmentN.

I'd like to write:

class SomeClass{
    private {FragmentImplementsIMyFragment} mFragment;

    ...
    mFragment = new MyFragment();
    ...
    mFragment = new MyListFragment();
}

I need both behaviors: from Fragment and from IMyFragment.

Was it helpful?

Solution 2

The best I achieved is adding to IMyFragment method:

Fragment getFragment();

and implementing it always:

Fragment getFragment() { return this; }

OTHER TIPS

Is there any way to create field typed by Fragment which implements IMyFragment? So both 'MyListFragment' and 'MyFragment' would be correct type for it?

Depending on what is the really your goal, you may want to either use IMyFragment as your type, or do some checks in code to see if your Fragment implements required interface. You can also check what is the class the of created object and act accordingly

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top