Кинжал 2 инъекционный предмет - PullRequest
0 голосов
/ 29 августа 2018

Я сделал нижнюю полосу андроида в действии и подумал, что буду использовать 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;
}
}

И нужно получить фрагменты supportManager здесь

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;
}
}

Как мне это сделать?

1 Ответ

0 голосов
/ 29 августа 2018

Вам нужно поделиться экземпляром 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);
}
...

Но очень странная вещь, которую вы пытаетесь сделать. Все это эквивалентно передаче FragmentManager непосредственно в BottomNavigationListener без использования Dagger.

...