dagger.android--Fragment,BaseFragment

2020-11-22 21:00:28

参考地址 Android开发之dagger.android--Fragment

前言

在上一篇文章中 Android开发之dagger.android--Activity,主要是使用Dagger-Android注入到Activity中,上文结尾也说到,Dagger-Android也可以注入到Fragment,BroadcastReceiver等,这篇文章就就讨论使用Dagger-Android注入到Fragment和BroadcastReceiver。
详情请参照Dagger-Android官方文档 官网传送门

代码已提交到github
代码传送门

注入Fragment实例

注入Fragment和注入Activity是一样的,以相同的方式定义subcomponent,不同有以下几点是不同的。

  • 1 使用Fragment参数来代替Activity参数

  • 2 使用 @FragmentKey来代替@ActivityKey

  • 3 使用HasFragmentInjector来代替@HasActivityInjector

  • 4 AndroidInjection.inject(Fragment)方法,在Fragment的onAttach()中调用,而不是在onCreate()中

  • 5 Fragment的Module添加位置,和Activity是不同的,它取决于Fragment需要的其他依赖注入

和Activity定义modules的不同,你可以选择在什么地方为Fragment安装module模块,你可以使你的Fragment component成为另一个Fragment component, Activity component, 或者 Application component 的subcomponent ,这一切都依赖于你的Fragment需要的其他绑定。在确定了component 的位置之后,使相应的类型实现HasFragmentInjector。

上代码

步骤一: 和Fragment绑定的Activity实现HasFragmentInjector接口
在这里主要完成:

  1. 在super.onCreate(savedInstanceState);前完成AndroidInjection.inject(this); 实现Activity的注入。

  2. 实现supportFragmentInjector()方法,返回fragmentInjector。

public class DaggerFragmentActivity extends AppCompatActivity implements HasSupportFragmentInjector{

    @Inject
    DispatchingAndroidInjector<Fragment> fragmentInjector;

    ViewPager viewPager;
    ArrayList<Fragment> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        AndroidInjection.inject(this);  // 实现Activity的注入

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dagger_fragment);
        init();

    }

    private void init() {
        viewPager = (ViewPager) findViewById(R.id.viewPager);
        // 初始化ViewPager对象中所需要的数据
        list = new ArrayList<Fragment>();
        list.add(new Fragment01());
        list.add(new Fragment02());
        list.add(new Fragment03());
        list.add(new Fragment04());

        viewPager.setAdapter(new MyAdapterState(getSupportFragmentManager()));
    }


  // 返回fragmentInjector
    @Override
    public AndroidInjector<Fragment> supportFragmentInjector() {
        return fragmentInjector;
    }}

注意:

  • 1 如果使用v4包中的Fragment(既android.support.v4.app.Fragment),应实现HasSupportFragmentInjector接口,应该实现

 @Override
    public AndroidInjector<Fragment> supportFragmentInjector() {
        return fragmentInjector;
    }
  • 2 如果使用普通的Fragment(即android.app.Fragment),应该实现HasFragmentInjector接口,应该实现

 @Override
    public AndroidInjector<android.app.Fragment> fragmentInjector() {
        return fragmentInjector;
    }

步骤二: 在Fragment01的onAttach()方法中,super.onAttach(context)方法前调用AndroidSupportInjection.inject(this)。

public class Fragment01 extends Fragment {

    private View mView;

    private TextView tv;

    @Inject
    Student mStudent;

    @Override
    public void onAttach(Context context) {
        AndroidSupportInjection.inject(this);  //  在这里完成
        super.onAttach(context);
    }

  
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        mView=inflater.inflate(R.layout.fragment_fragment01, container, false);
        Log.d("hbj--",mStudent.toString());
        tv=(TextView)mView.findViewById(R.id.frg_text);
        tv.setText(mStudent.showMessage());
        return mView;
    }}

注意:

  • 如果使用v4包中的Fragment,在onAttach()方法中,应调用AndroidSupportInjection.inject(this);

  • 如果使用普通的Fragment(即android.app.Fragment),在onAttach()方法中,应调用AndroidInjection.inject(this);
    步骤三:创建 Fragment对应的子组件Subcomponent,继承自AndroidInjector,子组件中含有一个抽象类Builder, 该Builder继承自AndroidInjector.Builder,并由@Subcomponent.Builder注解。

@Subcomponent(modules = {AndroidInjectionModule.class, Fragment01Module.class})public interface DaggerFragmentActSubComponent extends AndroidInjector<DaggerFragmentActivity>{

    @Subcomponent.Builder     abstract class Builder extends AndroidInjector.Builder<DaggerFragmentActivity>{

    }}

步骤四:创建 Fragment对应的Module,关联subcomponents,在这里可以提供Fragment01需要的实例(这里提供的是Student实例)。

@Module(subcomponents = Fragment01Subcomponent.class)public abstract class Fragment01Module {
    @Binds
    @IntoMap
    @FragmentKey(Fragment01.class)
    abstract AndroidInjector.Factory<? extends Fragment> bindFragment01InjectorFactory(Fragment01Subcomponent.Builder builder);

    @Provides
    static Student provideStudent() {
        return new Student();
    }}

步骤五:将该Module注入到和Fragment01绑定的Activity的子组件SubComponent中。以下是和Fragment01关联的SubComponent和Module,参见是上篇文章 Android开发之dagger.android--Activity的用法

@Subcomponent(modules = {AndroidInjectionModule.class, Fragment01Module.class})public interface DaggerFragmentActSubComponent extends AndroidInjector<DaggerFragmentActivity>{

    @Subcomponent.Builder     abstract class Builder extends AndroidInjector.Builder<DaggerFragmentActivity>{

    }}

@Module(subcomponents = DaggerFragmentActSubComponent.class)public abstract class DaggerFragmentActModule {

    @Binds
    @IntoMap
    @ActivityKey(DaggerFragmentActivity.class)
    abstract AndroidInjector.Factory<? extends Activity> bindDaggerFragmentActivityInjectorFactory(DaggerFragmentActSubComponent.Builder builder);}

编译运行,可以看到Fragment01实例注入成功。

进一步改进

参照上篇文章进一步改进,直接上代码。

  • 1 新建BaseFragment,在BaseFragment里执行 AndroidInjection.inject(this)或者 AndroidSupportInjection.inject(this);

public class BaseFragment extends Fragment{

    @Override
    public void onAttach(Context context) {
        AndroidSupportInjection.inject(this);
        super.onAttach(context);
    }}

并将所有Fragment继承自BaseFragment

public class Fragment01 extends BaseFragment {
  • 2 新建BaseFragmentSubcomponent,在这里我们AndroidInjector.Builder的是上部新建的BaseFragment。

@Subcomponent(modules = {AndroidInjectionModule.class})public interface BaseFragmentSubcomponent extends AndroidInjector<BaseFragment>{
    @Subcomponent.Builder
    public abstract class Builder extends AndroidInjector.Builder<BaseFragment>{

    }}
  • 3 新建一个AllFragmentsModule,子部件为上部新建的BaseFragmentSubcomponent,在这里提供所有的AFragmentModule,每个都用@ContributesAndroidInjector注解。

@Module(subcomponents = BaseFragmentSubcomponent.class)public abstract class AllFragmentsModule {

    @ContributesAndroidInjector(modules = Fragment01ProModule.class)
    abstract Fragment01 contributeFragment01Injector();}
  • 4 修改Fragment01ProModule,变成一个普通的Module,和前文对比,删掉了(subcomponents = Fragment01Subcomponent.class)以及bindFragment01InjectorFactory抽象方法。在这里可以根据需要提供实例。

@Modulepublic abstract class Fragment01ProModule {

    @Provides
    static Student provideStudent() {
        return new Student();
    }
  • 5  修改AppComponent,把AllFragmentsModule.class放进modules中。

@Singleton@Component(modules = {AndroidInjectionModule.class, AppModule.class, AllActivitysModule.class, AllFragmentsModule.class})public interface AppComponent {
    void inject(MyApplication application);}

编译以后可是可以运行的。

总结

经过改进,如果我们新添了新的Fragment,我们只要下面的步骤:

  • 1.新Fragment继承BaseFragment。


    1. 为新Fragment建一个NewFragmentModule,这是一个普通的Module,用@Module注解,在这提提供新Fragment需要的实例。注意要用static关键字哦。

  • 3 新Fragment添加到AllFragmentsModule 中,类似于下面的代码。

@Module(subcomponents = BaseFragmentSubcomponent.class)public abstract class AllFragmentsModule {

    @ContributesAndroidInjector(modules = Fragment01ProModule.class)
    abstract Fragment01 contributeFragment01Injector();

    @ContributesAndroidInjector(modules = Fragment02ProModule.class)
    abstract Fragment02 contributeFragment02Injector();}

参照官网,经过改进,注入过程更加简洁。
代码传送门

Dagger-Android还提供了BroadcastReceiver,Service等其他组件的注入方式,具体可以参照官网 官网传送门
,我们就不再讨论了。



  • 2017-10-16 16:45:45

    Android开发技巧:Application和Instance

    在开发过程中,我们经常会需要用到一些全局的变量或者全局的“管理者”,例如QQ,需要有一个“全局的管理者“保存好友信息,各个activity即可直接通过该”管理者“来获取和修改某个好友信息,显然,这样的一个好友信息,保存到某一个具体的activity里面,然后依靠activity的intent来传递参数是不合适。我们有两种方法来实现这样一个全局的管理者,一种是使用C++/Java中常用的单例模式,另一种是利用Android的Application类,下面一一阐述。

  • 2017-11-01 01:30:45

    解决第三方包内jar包冲突

    这个问题就是因为引入jar包的冲突,这时我们可以在build.gradle中添加如下代码,下方单独的是添加的代码

  • 2017-11-06 01:00:17

    撤销git add

    如何撤销git add,不小心执行了git add . 操作,但是又不能提交所有的文件,因为对应不同的分支,现在怎么样可以将git add 撤销回来

  • 2017-11-10 00:06:15

    CORS: credentials mode is 'include'

    XMLHttpRequest cannot load http://localhost/Foo.API/token. The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:5000' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.