简体   繁体   English

Android类层次结构和Fragment接口

[英]Android class hierarchy and interfaces with Fragment

I have two Fragment hierarchy: 我有两个Fragment层次结构:

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

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

Both MyAbstractFragmentN and MyAbstractListFragmentN implements IMyFragment , so both MyFragment and MyListFragment implemets this interface too. MyAbstractFragmentNMyAbstractListFragmentN实现IMyFragment ,因此MyFragmentMyListFragment实现了此接口。

Is there any way to create field typed by Fragment which implements IMyFragment ? 有什么方法可以创建由实现IMyFragmentFragment类型的字段? So both 'MyListFragment' and 'MyFragment' would be correct type for it? 那么'MyListFragment'和'MyFragment'都是正确的类型吗?

I can't create super class from both MyFragment and MyListFragment would inherit, because there are very different from the beginning. 我不能从MyFragmentMyListFragment都继承来创建超类,因为与开始有很大的不同。 They have only Fragment in common, and IMyFragment from MyAbstractListFragmentN and MyAbstractFragmentN . 他们只有Fragment中常见的, IMyFragmentMyAbstractListFragmentNMyAbstractFragmentN

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 . 我需要两种行为:来自Fragment和来自IMyFragment

Is there any way to create field typed by Fragment which implements IMyFragment? 有什么方法可以创建由实现IMyFragment的Fragment类型的字段? So both 'MyListFragment' and 'MyFragment' would be correct type for it? 那么'MyListFragment'和'MyFragment'都是正确的类型吗?

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. 根据您真正的目标是什么,您可能要使用IMyFragment作为您的类型,或者在代码中进行一些检查以查看您的Fragment是否实现了必需的接口。 You can also check what is the class the of created object and act accordingly 您还可以检查所创建对象的类是什么,并采取相应的措施

The best I achieved is adding to IMyFragment method: 我取得的最好成绩是添加到IMyFragment方法:

Fragment getFragment();

and implementing it always: 并始终执行:

Fragment getFragment() { return this; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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