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等其他组件的注入方式,具体可以参照官网 官网传送门
,我们就不再讨论了。



  • 2019-09-26 18:57:29

    Java中数组怎么深度复制

    有时候循环进行一些操作,放入list,发现,list中的数据都是一个数据,这就尴尬了,我们需要深度复制,才能解决这个问题。或者生成新的,也就是深度复制。

  • 2019-09-26 19:03:33

    spring post jackson的反序列化需要无参构造函数

    JSON parse error: Cannot construct instance of `com.**` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.**` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator)  at [Source: (PushbackInputStream); line: 2, column: 2]] ———————————————— 版权声明:本文为CSDN博主「冰夏之夜影」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/u011561335/article/details/91346777

  • 2019-09-26 21:46:36

    Shiro整合JWT+Token过期刷新,demo,详解

    最近使用SpringBoot集成Shiro,JWT快速搭建了一个后台系统,Shiro前面已经使用过,JWT(JSON Web Tokens)是一种用于安全的传递信息而采用的一种标准。Web系统中,我们使用加密的Json来生成Token在服务端与客户端无状态传输,代替了之前常用的Session。 系统采用Redis作为缓存,解决Token过期更新的问题,同时集成SSO登录,完整过程这里来总结一下。

  • 2019-09-26 21:48:15

    解决UEditor超出最大字数后只提示不限制的问题

    最近项目用到百度额UEditor文本编辑器,今天测试向我提出了一个问题。就是在输入的文字超过默认的最大字数限制之后,虽然提示“字数超过最大范围,服务器可能拒绝保存”,但是仍然可以点击保存按钮进行保存。

  • 2019-09-27 14:49:33

    Google Guava介绍和体检

    JDK提供的String还不够好么?也许还不够友好,至少让我们用起来还不够爽,还得操心!举个栗子,比如String提供的split方法,我们得关心空字符串吧,还得考虑返回的结果中存在null元素吧,只提供了前后trim的方法(如果我想对中间元素进行trim呢)。

  • 2019-09-28 00:03:21

    shiro的session共享,持久化

     shiro的session创建与session的查询、更新、过期、删除中,shiro对session的操作基本都讲到了,但还缺一个session共享没有讲解;session共享的原理其实在自定义session管理一文已经讲过了,本文不讲原理,只看看shiro的session共享的实现。