Android片段和依赖注入

The*_*ter 10 dependencies android dependency-injection code-injection fragment

正如标题所说,我试图弄清楚哪一个是在片段中注入依赖的最佳方式.我希望独立于RoboGuice等外部框架.

现在,以最简单的方式,我有一个抽象某种逻辑的接口,并且,从一个Activity,我想注入一个这个接口的实现.我知道我必须为我的片段提供一个默认构造函数,因为系统可能需要在某个时刻重新创建片段,并且创建片段的新实例的常用方法是提供处理创建的静态方法这个:

public static Fragment newInstance() {
    final Bundle bundle = new Bundle();
    ...
    final Fragment fragment = new MyFragment();
    fragment.setArguments(bundle);
    return fragment;
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能将依赖关系传递给片段?我应该让它实现Parcelable或Serializable接口,然后将它打包到Bundle中吗?有没有其他方法来实现结果?

joe*_*cks 9

一个简单的解决方案是声明一个接口,该接口声明Fragment所需的依赖关系.然后让Fragment的Context实现此接口,并在需要时从Context中轮询依赖项.

合同:

public interface MyDependencies {

    MyDep getDep();

}
Run Code Online (Sandbox Code Playgroud)

活动:

public MyActivity extends Activity implements MyDependencies {

    @Override
    public MyDep getDep(){
       return createMyDependencyOrGetItFromASingletonOrGetItFromApplication()
    }
}
Run Code Online (Sandbox Code Playgroud)

分段:

public void onActivityCreated(Bundle b){
     super.onActivityCreated(b)

     if (getActivity() instanceOf MyDependencies) {
         MyDep dep = ((MyDependencies) getActivity).getDep();
     } else {
         throw new RuntimeException("Context does not support the Fragment, implement MyDependencies")
     }
}
Run Code Online (Sandbox Code Playgroud)

因此,实际上,没有不必要的与Activity的耦合,因为契约是由接口定义的.


Jul*_*rez -1

为什么不从你的活动中获取依赖性呢?

public void onActivityCreated( Bundle b){
     super.onActivityCreated(b)
     DependencyClass c = ((MyActivity)getActivity()).getDependency();
}
Run Code Online (Sandbox Code Playgroud)

  • 如果我这样做,我最终会将片段耦合到活动,对吧?我还是希望Fragment是独立的、可重用的。 (3认同)