我正在使用以下 google 示例项目:https ://github.com/googlesamples/android-architecture-components作为我的新项目的参考,并且在尝试向项目添加第二个活动时遇到困难。
这是我在编译时遇到的错误
Error:(22, 8) error: [dagger.android.AndroidInjector.inject(T)] com.apps.myapp.ui.common.MainActivity cannot be provided without an @Inject constructor or from an @Provides-annotated method. This type supports members injection but cannot be implicitly provided.
com.apps.myapp.ui.common.MainActivity is injected at
com.apps.myapp.ui.common.NavigationController.<init>(mainActivity)
com.apps.myapp.ui.common.NavigationController is injected at
com.apps.myapp.ui.addContacts.AddContactsFragment.navigationController
com.apps.myapp.ui.addContacts.AddContactsFragment is injected at
dagger.android.AndroidInjector.inject(arg0)
A binding with matching key exists in component: com.apps.myapp.di.ActivityModule_ContributeMainActivity.MainActivitySubcomponent
这是我的代码
活动模块
@Module
public abstract class ActivityModule {
@ContributesAndroidInjector(modules = FragmentBuildersModule.class)
abstract MainActivity contributeMainActivity();
@ContributesAndroidInjector(modules = FragmentBuildersModule.class)
abstract ContactActivity contributeContactActivity();
}
应用组件
@Singleton
@Component(modules = {
AndroidInjectionModule.class,
AppModule.class,
ActivityModule.class})
public interface AppComponent {
@Component.Builder
interface Builder {
@BindsInstance Builder application(Application application);
AppComponent build();
}
void inject(App app);
}
应用程序注入器
public class AppInjector {
private AppInjector() {}
public static void init(App app) {DaggerAppComponent.builder().application(app).build().inject(app);
app.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
handleActivity(activity);
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
});
}
private static void handleActivity(Activity activity) {
if (activity instanceof HasSupportFragmentInjector) {
AndroidInjection.inject(activity);
}
if (activity instanceof FragmentActivity) {
((FragmentActivity) activity).getSupportFragmentManager()
.registerFragmentLifecycleCallbacks(
new FragmentManager.FragmentLifecycleCallbacks() {
@Override
public void onFragmentCreated(FragmentManager fm, Fragment f,
Bundle savedInstanceState) {
if (f instanceof Injectable) {
AndroidSupportInjection.inject(f);
}
}
}, true);
}
}
}
应用模块
@Module(includes = ViewModelModule.class)
class AppModule {
@Singleton @Provides
BnderAPIService provideService() {
return new Retrofit.Builder()
.baseUrl("serverurl")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(new LiveDataCallAdapterFactory())
.build()
.create(APIService.class);
}
@Singleton @Provides
Db provideDb(Application app) {
return Room.databaseBuilder(app, Db.class,"Db.db").build();
}
@Singleton @Provides
UserDao provideUserDao(Db db) {
return db.userDao();
}
@Singleton @Provides
ContactDao provideContactDao(Db db) {
return db.contactDao();
}
}
FragmentBuilders 模块
@Module
public abstract class FragmentBuildersModule {
@ContributesAndroidInjector
abstract AddContactsFragment contributeAddUserFragment();
@ContributesAndroidInjector
abstract ContactsFragment contributeContactsFragment();
@ContributesAndroidInjector
abstract ChalkboardFragment contributeChalkboardFragment();
}
可注射的
public interface Injectable {
}
视图模型键
@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@MapKey
@interface ViewModelKey {
Class<? extends ViewModel> value();
}
视图模型模块
@Module
abstract class ViewModelModule {
@Binds
@IntoMap
@ViewModelKey(AddContactsViewModel.class)
abstract ViewModel bindAddContactsViewModel(AddContactsViewModel addContactsViewModel);
@Binds
@IntoMap
@ViewModelKey(ContactsViewModel.class)
abstract ViewModel bindContactsViewModel(ContactsViewModel contactsViewModel);
@Binds
@IntoMap
@ViewModelKey(ChalkboardViewModel.class)
abstract ViewModel bindChalkboardViewModel(ChalkboardViewModel chalkboardViewModel);
@Binds
abstract ViewModelProvider.Factory bindViewModelFactory(ViewModelFactory factory);
}
应用
public class App extends Application implements HasActivityInjector {
@Inject
DispatchingAndroidInjector<Activity> dispatchingAndroidInjector;
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
@Override
public void onCreate() {
super.onCreate();
if (BuildConfig.DEBUG) {
}
AppInjector.init(this);
}
@Override
public DispatchingAndroidInjector<Activity> activityInjector() {
return dispatchingAndroidInjector;
}
}
导航控制器
public class NavigationController {
private final int containerId;
private final FragmentManager fragmentManager;
@Inject
public NavigationController(MainActivity mainActivity) {
this.containerId = R.id.container;
this.fragmentManager = mainActivity.getSupportFragmentManager();
}
public void navigateToUsers() {
Log.i("TAG", "Navigate to users");
String tag = "users";
AddContactsFragment userFragment = AddContactsFragment.create();
fragmentManager.beginTransaction()
.replace(containerId, userFragment, tag)
.addToBackStack(null)
.commitAllowingStateLoss();
}
public void navigateToContacts() {
Log.i("TAG", "Navigate to contacts");
String tag = "contacts";
ContactsFragment contactsFragment = ContactsFragment.create();
fragmentManager.beginTransaction()
.add(contactsFragment, tag)
.addToBackStack(null)
.commitAllowingStateLoss();
}
public void navigateToChalkboard() {
Log.i("TAG", "Navigate to chalkboard");
String tag = "chalkboard";
ChalkboardFragment chalkboardFragment = ChalkboardFragment.create();
fragmentManager.beginTransaction()
.add(chalkboardFragment, tag)
.addToBackStack(null)
.commitAllowingStateLoss();
}
}
主要活动
public class MainActivity extends AppCompatActivity implements LifecycleRegistryOwner, HasSupportFragmentInjector {
private final LifecycleRegistry lifecycleRegistry = new LifecycleRegistry(this);
@Inject
DispatchingAndroidInjector<Fragment> dispatchingAndroidInjector;
@Inject
NavigationController navigationController;
private Toolbar toolbar;
@Override
public LifecycleRegistry getLifecycle() {
return lifecycleRegistry;
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.setHandler(this);
binding.setManager(getSupportFragmentManager());
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
@Override
public DispatchingAndroidInjector<Fragment> supportFragmentInjector() {
return dispatchingAndroidInjector;
}
static class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
@BindingAdapter({"handler"})
public static void bindViewPagerAdapter(final ViewPager view, final MainActivity activity) {
final ViewPagerAdapter adapter = new ViewPagerAdapter(activity.getSupportFragmentManager());
adapter.addFragment(new ChalkboardFragment(), "Chalkboard");
adapter.addFragment(new ContactsFragment(), "Contacts");
view.setAdapter(adapter);
}
@BindingAdapter({"pager"})
public static void bindViewPagerTabs(final TabLayout view, final ViewPager pagerView) {
view.setupWithViewPager(pagerView, true);
}
}
联系活动
public class ContactActivity extends AppCompatActivity implements LifecycleRegistryOwner, HasSupportFragmentInjector {
private final LifecycleRegistry lifecycleRegistry = new LifecycleRegistry(this);
@Inject
DispatchingAndroidInjector<Fragment> dispatchingAndroidInjector;
@Override
public LifecycleRegistry getLifecycle() {
return lifecycleRegistry;
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact);
if (savedInstanceState == null) {
}
}
@Override
public DispatchingAndroidInjector<Fragment> supportFragmentInjector() {
return dispatchingAndroidInjector;
}
}