我在活动中制作了一个android底部栏,并认为我会使用dagger2为其设置侦听器。我如何对如何在监听器类中获取 getSupportFragmentManager()感到困惑。 这就是我正在尝试的
public class MainActivity extends AppCompatActivity {
@BindView(R.id.bottomNavigationView)
BottomNavigationView bottomNavigationView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
BottomBarComponent bottomBarComponent = DaggerBottomBarComponent.builder()
.bottomBarModule(new BottomBarModule(getSupportFragmentManager()))
.build();
}
}
组成部分是
@Singleton
@Component(modules = {BottomBarModule.class})
public interface BottomBarComponent {
void inject(BottomNavigationListener listener);
}
模块是
@Module
public class BottomBarModule {
private FragmentManager manager;
public BottomBarModule(FragmentManager context) {
this.manager = context;
}
@Singleton
@Provides
public FragmentManager provideSupportManager(){
return manager;
}
}
并且需要在此处获取fragmentsupportManager
public class BottomNavigationListener implements BottomNavigationView.OnNavigationItemSelectedListener{
@Inject
FragmentManager manager;
public void BottomNavigationListener() {
//somehow need to get fragmentSupportManager here
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
return true;
}
}
我该怎么做?
答案 0 :(得分:0)
您需要与BottomBarComponent
共享BottomNavigationListener
的实例,并在其上调用inject()
方法。
BottomNavigationListener.class
...
public void BottomNavigationListener(BottomBarComponent injector) {
//somehow need to get fragmentSupportManager here
injector.inject(this); // now manager field must be filled
}
...
MainActivity.class
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
BottomBarComponent bottomBarComponent = DaggerBottomBarComponent.builder()
.bottomBarModule(new BottomBarModule(getSupportFragmentManager()))
.build();
// pass BottomBarComponent to BottomNavigationListener for injecting FragmentManager
BottomNavigationListener listener = new BottomNavigationListener(bottomBarComponent);
}
...
但是您要尝试做的事情很奇怪。等同于无需使用Dagger就将FragmentManager
直接传递到BottomNavigationListener
。