gpt4 book ai didi

java - Dagger 2 Inject 注释破坏了注入(inject)

转载 作者:行者123 更新时间:2023-11-30 10:40:53 25 4
gpt4 key购买 nike

我正在使用 dagger 2 将 FragmentManager 和 FragmentTransaction 注入(inject)到我的 Activity 中。一切看起来都很好,直到我添加

@Inject
FragmentManager fragmentManager;

@Inject
FragmentTransaction fragmentTransaction

进入我的 Activity ,如下所示在重建时引发错误:

Error:(21, 10) error: android.support.v4.app.FragmentManager cannot be provided without an @Provides- or @Produces-annotated method. android.support.v4.app.FragmentManager is injected at com.toranj.tyke.ui.MainActivity.fragmentManager com.toranj.tyke.ui.MainActivity is injected at com.toranj.tyke.dagger.components.LotteryComponent.inject(activity)

这是模块:

@Module
public class FragmentModule {

FragmentActivity activity;

public FragmentModule(FragmentActivity activity) {
this.activity = activity;
}

@Provides
@PerActivity
public FragmentManager providesFragmentManager() {
return activity.getSupportFragmentManager();
}

@Provides
@PerActivity
public FragmentTransaction providesFragmentTransaction() {
return activity.getSupportFragmentManager().beginTransaction();
}
}

这是组件:

@PerActivity
@Component(modules = FragmentModule.class)
public interface FragmentComponent {
void inject(Activity activity);

FragmentManager fragmentManager();
FragmentTransaction fragmentTransaction();
}

这是我的 Activity :

public class MainActivity extends AppCompatActivity {

@Inject
FragmentManager fragmentManager;

@Inject
FragmentTransaction fragmentTransaction;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

FragmentComponent fragmentComponent = DaggerFragmentComponent.builder()
.fragmentModule(new FragmentModule(this))
.build();
fragmentComponent.inject(this);
}
}

我对使用 Dagger 和依赖注入(inject)还很陌生,我可能错过了上面某处的一点。任何带解释的答案都将帮助我理解注入(inject),也非常感谢。

编辑:模块、组件和 Activity 中使用的所有 fragmentManager 都来自 android.support.v4.app.FragmentManager

最佳答案

我猜 android.app.FragmentManager 被用于 FragmentComponent

android.support.v4.app.FragmentManager 应该改用。

关于java - Dagger 2 Inject 注释破坏了注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38725983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com