gpt4 book ai didi

android - Dagger 2 - 将 FragmentManager 传递给构造函数

转载 作者:太空狗 更新时间:2023-10-29 16:00:04 24 4
gpt4 key购买 nike

我正在研究 Dagger 2 库并遇到传递无法从“扩展应用程序”类获取的参数的问题。

例如,我需要将 FragmentManager 传递给 ViewPager 适配器构造函数。 你会怎么做?

我的申请:

public class MyApplication extends Application {

private MyAppComponent mMyAppComponent;

@Override
public void onCreate() {
super.onCreate();

Context context = getApplicationContext();

mMyAppComponent= DaggerMyAppComponent.builder()
.utilityModule(new UtilityModule())
.locationModule(new LocationModule(context))
.appModule(new AppModule(context))
.pagerAdapterModule(new PagerAdapterModule(context)) //this one is problematic
.build();
}

public MyAppComponent getmMyAppComponent() {
return mMyAppComponent;
}
}

我的应用组件:

@Singleton
@Component(
modules = {
UtilityModule.class,
LocationModule.class,
PagerAdapterModule.class,
AppModule.class
}

)

public interface MyComponent {
FragmentManager fragmentManager(); //is it right?

public void inject(NavigationActivity navigationActivity);
}

应用模块:

@Module
public class AppModule {
Context context;

public AppModule(Context context) {
this.context = context;
}

@Provides
@Singleton
Context provideApplicationContext() {
return context;
}
}

PagerAdapterModule:

@Module
public class PagerAdapterModule {
Context context;

public PagerAdapterModule(Context context) {
this.context = context;
}

@Provides
@Singleton TabsPagerAdapter provideTabsPagerAdapter(FragmentManager fragmentManager) {
return new TabsPagerAdapter(context, fragmentManager);
}
}

导航 Activity :

@Inject TabsPagerAdapter mTabsAdapter; //I want this to be initialized 

最佳答案

您需要有一个FragmentActivity 才能获得一个FragmentManager,这意味着您无法在Application 级别完成它,因为它太早了。因此,您必须从 AppComponent 创建一个组件依赖项,我们将其命名为 ActivityComponent,它将看到 AppComponent 提供的所有依赖项。

@Component(modules = ActivityModule.class, dependencies = MyAppComponent.class)
public interface ActivityComponent {
void inject(MainActivity mainActivity);
}

@Module
public class ActivityModule {

FragmentActivity activity;

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

@Provides
TabsPagerAdapter provideTabsPagerAdapter() {
return new TabsPagerAdapter(activity, activity.getSupportFragmentManager());
}
}

现在在您 Activity 的 onCreate() 中:

public class MainActivity extends AppCompatActivity {

@Inject
TabsPagerAdapter tabsPagerAdapter;

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

ActivityComponent activityComponent = DaggerActivityComponent.builder()
.activityModule(new ActivityModule(this))
.myAppComponent(MyApplication.getMyAppComponent())
.build();

activityComponent.inject(this);
}

}

关于android - Dagger 2 - 将 FragmentManager 传递给构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38371106/

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