简体   繁体   中英

Android class hierarchy and interfaces with Fragment

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 .

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

The best I achieved is adding to IMyFragment method:

Fragment getFragment();

and implementing it always:

Fragment getFragment() { return this; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM